在做TCP數(shù)據(jù)傳輸中史飞,協(xié)議往往需要傳輸?shù)氖荁yte數(shù)組朴则,而在iOS中我們常常都是發(fā)送的NSData類型爽丹,這時(shí)我們就需要轉(zhuǎn)化勤篮。具體操作如下:
- Byte 轉(zhuǎn)化為 NSData
Byte byte[] = {0x55, 0x07, 0x02, 0x01, 0x1A, 0x01, 0xAA};
NSData *data = [NSData dataWithBytes:byte lenght:7];
- NSData 轉(zhuǎn)化為 Byte
NSString *testString = @"1234567890";
NSData *testData = [testString dataUsingEncoding: NSUTF8StringEncoding];
Byte *testByte = (Byte *)[testData bytes];
- int 轉(zhuǎn)化為 NSData
int i = 1;
NSData *data = [NSData dataWithBytes:&i length: sizeof(i)];
- NSData 轉(zhuǎn)化為 int
int k;
[data getBytes: &k length: sizeof(k)];
- NSData 轉(zhuǎn)化為 NSString
NSString *aString = [[NSString alloc] initWithData:adata encoding:NSUTF8StringEncoding];
- NSString 轉(zhuǎn)化為 NSData
NSString *aString = @"1234";
NSData *aData = [aString dataUsingEncoding: NSUTF8StringEncoding];
- UIImage 轉(zhuǎn)化為 NSData
NSData *imageData = UIImagePNGRepresentation(image);
- NSData 轉(zhuǎn)化為 UIImage
NSData *imageData = [NSData dataWithContentsOfFile: filePath];
UIImage *image = [UIImage imageWithData: imageData];
注意
假如你們公司后臺是java開發(fā)的乳附,而之間又要進(jìn)行數(shù)據(jù)傳輸内地,那么****可能 ****就會涉及大小端的數(shù)據(jù)問題。因?yàn)閖ava默認(rèn)是大端赋除,iOS采用的是小端模式阱缓,所以需要轉(zhuǎn)化。具體操作如下:
- 先進(jìn)行大小端判斷
int checkCPUendian() {//返回1举农,為小端荆针;反之,為大端颁糟;
union
{
unsigned int a;
unsigned char b;
}c;
c.a = 1;
return 1 == c.b;
}
- 再將小端轉(zhuǎn)化為大端, 利用C語言函數(shù)
ntohl()
進(jìn)行轉(zhuǎn)換
int newSize = size;
if (checkCPUendian() == 1) {
newSize = ntohl(size);//小端轉(zhuǎn)大端
}