解决问题@"FE010000000429C6"转换为<FE010000 000429C6> ;
先初始化一个可变Data作最后的输出结果:
NSMutableData*data=[[NSMutableData alloc]init];
NSString*commondStr=@"FE010000000429C6";
64位系统下的做法:
unsigned long hexData=strtoul([commondStr UTF8String],NULL,16);
[data appendBytes:&hexData length:sizeof(hexData)];
经测试,在32位系统的老机型上输出均为,在64位系统下输出为。
标准做法: 将方法写入NSString的扩展:
+(NSData*)stringToHexData:(NSString*)hexStr{
unsigned long len=[hexStr length]/2; // Target length
unsigned char*buf=malloc(len);
unsigned char*whole_byte=buf;
char byte_chars[3]={'\0','\0','\0'};
for(int i=0;i<[hexStr length]/2;i++){
byte_chars[0]=[hexStr characterAtIndex:i*2];
byte_chars[1]=[hexStr characterAtIndex:i*2+1];
*whole_byte=strtol(byte_chars,NULL,16);
whole_byte++;
}
NSData*data=[NSData dataWithBytes:buf length:len];
free(buf);
return data;
}
使用:
[data appendData:[NSString stringToHexData:commondStr]];
附:16进制data转会NSString对象的方法
+(NSString*)hexStringFromData:(NSData*)myD{
Byte*bytes=(Byte*)[myD bytes];//下面是Byte 转换为16进制。 NSString*hexStr=@"";
for(int i=0;i<[myD length];i++){
NSString*newHexStr=[NSString stringWithFormat:@"%x",bytes[i]&0xff]; if([newHexStr length]==1){
hexStr=[NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
} else {
hexStr=[NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
}
return hexStr;
}
链接地址:https://segmentfault.com/n/1330000007028397