一.byte数组生成NSData
Byte byte[] = {0x40,0xff,0x04,0x80,0x01,0x66,0xef,0xda,0xb9,0x0d,0x0a};
NSData *adata = [[NSData alloc] initWithBytes:byte length:11];
NSData *imageData = [NSData dataWithBytes:byte length:sizeof(byte)];
NSLog(@"%@",imageData);
//可用于解析NSData
Byte *bytes = (Byte *)[adata bytes];
NSString *hexStr=@"";
for(int i=0;i<[adata length];i++)
{
NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff];///16进制数
if([newHexStr length]==1)
hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
else
hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
}
NSLog(@"bytes 的16进制数为:%@",hexStr);
二.
/ 将16进制数据转化成Byte 数组
NSString *hexString = @"3e435fab9c34891f"; //16进制字符串
int j=0;
Byte *bytes; //
for(int i=0;i<[hexString length];i++)
{
int int_ch; /// 两位16进制数转化后的10进制数
unichar hex_char1 = [hexString characterAtIndex:i]; 两位16进制数中的第一位(高位*16)
int int_ch1;
if(hex_char1 >= '0' && hex_char1 <='9')
int_ch1 = (hex_char1-48)*16; 0 的Ascll - 48
else if(hex_char1 >= 'A' && hex_char1 <='F')
int_ch1 = (hex_char1-55)*16; A 的Ascll - 65
else
int_ch1 = (hex_char1-87)*16; a 的Ascll - 97
i++;
unichar hex_char2 = [hexString characterAtIndex:i]; ///两位16进制数中的第二位(低位)
int int_ch2;
if(hex_char2 >= '0' && hex_char2 <='9')
int_ch2 = (hex_char2-48); 0 的Ascll - 48
else if(hex_char1 >= 'A' && hex_char1 <='F')
int_ch2 = hex_char2-55; A 的Ascll - 65
else
int_ch2 = hex_char2-87; a 的Ascll - 97
int_ch = int_ch1+int_ch2;
NSLog(@"int_ch=%d",int_ch);
bytes[j] = int_ch; ///将转化后的数放入Byte数组里
j++;
}
NSData *newData = [[NSData alloc] initWithBytes:bytes length:sizeof(bytes)];
NSLog(@"newData=%@",newData);