NSData 和数据类型间的转换

2019-05-28  本文已影响0人  林初盛

在做TCP数据传输中,协议往往需要传输的是Byte数组,而在iOS中我们常常都是发送的NSData类型,这时我们就需要转化。具体操作如下:

Byte byte[] = {0x55, 0x07, 0x02, 0x01, 0x1A, 0x01, 0xAA};
NSData *data = [NSData dataWithBytes:byte lenght:7];
NSString *testString = @"1234567890";  
NSData *testData = [testString dataUsingEncoding: NSUTF8StringEncoding];  
Byte *testByte = (Byte *)[testData bytes];
int i = 1;
NSData *data = [NSData dataWithBytes:&i length: sizeof(i)];
int k;
[data getBytes: &k length: sizeof(k)];
* NSData 转化为 NSString
NSString *aString = [[NSString alloc] initWithData:adata encoding:NSUTF8StringEncoding];
NSString *aString = @"1234";
NSData *aData = [aString dataUsingEncoding: NSUTF8StringEncoding];
char *str = "123456789";
 NSData *data = [NSData dataWithBytes:str length:strlen(str)];
 NSString *strN = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
 NSLog(@"%@",strN);
NSData *imageData = UIImagePNGRepresentation(image);
NSData *imageData = [NSData dataWithContentsOfFile: filePath];  
UIImage *image = [UIImage imageWithData: imageData];
上一篇下一篇

猜你喜欢

热点阅读