NSData 和数据类型间的转换
2019-05-28 本文已影响0人
林初盛
在做TCP数据传输中,协议往往需要传输的是Byte数组,而在iOS中我们常常都是发送的NSData类型,这时我们就需要转化。具体操作如下:
- Byte 转化为 NSData
Byte byte[] = {0x55, 0x07, 0x02, 0x01, 0x1A, 0x01, 0xAA};
NSData *data = [NSData dataWithBytes:byte lenght:7];
- NSData 转化为 Byte
NSString *testString = @"1234567890";
NSData *testData = [testString dataUsingEncoding: NSUTF8StringEncoding];
Byte *testByte = (Byte *)[testData bytes];
- int 转化为 NSData
int i = 1;
NSData *data = [NSData dataWithBytes:&i length: sizeof(i)];
- NSData 转化为 int
int k;
[data getBytes: &k length: sizeof(k)];
* NSData 转化为 NSString
NSString *aString = [[NSString alloc] initWithData:adata encoding:NSUTF8StringEncoding];
- NSString 转化为 NSData
NSString *aString = @"1234";
NSData *aData = [aString dataUsingEncoding: NSUTF8StringEncoding];
- NSData 转化为 NSString
char *str = "123456789";
NSData *data = [NSData dataWithBytes:str length:strlen(str)];
NSString *strN = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",strN);
- UIImage 转化为 NSData
NSData *imageData = UIImagePNGRepresentation(image);
- NSData 转化为 UIImage
NSData *imageData = [NSData dataWithContentsOfFile: filePath];
UIImage *image = [UIImage imageWithData: imageData];