iOS中NSString转换成HEX(十六进制)-NSData转换成int

原创
2017/08/11 14:32
阅读数 1.4K
NSString *str = @"0xff055008";  
//先以16为参数告诉strtoul字符串参数表示16进制数字,然后使用0x%X转为数字类型  
unsigned long red = strtoul([str UTF8String],0,16);  
//strtoul如果传入的字符开头是“0x”,那么第三个参数是0,也是会转为十六进制的,这样写也可以:  
unsigned long red = strtoul([@"0x6587" UTF8String],0,0);  
NSLog(@"转换完的数字为:%lx",red);  

// 十六进制转换为普通字符串的。   
+ (NSString *)stringFromHexString:(NSString *)hexString { //   
   
charchar *myBuffer = (charchar *)malloc((int)[hexString length] / 2 + 1);   
bzero(myBuffer, [hexString length] / 2 + 1);   
for (int i = 0; i < [hexString length] - 1; i += 2) {   
unsigned int anInt;   
NSString * hexCharStr = [hexString substringWithRange:NSMakeRange(i, 2)];   
NSScanner * scanner = [[[NSScanner alloc] initWithString:hexCharStr] autorelease];   
[scanner scanHexInt:&anInt];   
myBuffer[i / 2] = (char)anInt;   
}   
NSString *unicodeString = [NSString stringWithCString:myBuffer encoding:4];   
NSLog(@"------字符串=======%@",unicodeString);   
return unicodeString;   
   
   
}   

//普通字符串转换为十六进制的。   
   
+ (NSString *)hexStringFromString:(NSString *)string{   
NSData *myD = [string dataUsingEncoding:NSUTF8StringEncoding];   
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];///16进制数   
   
if([newHexStr length]==1)   
   
hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];   
   
else   
   
hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];   
}   
return hexStr;   
}  


//int 转data  
int i = 1;   
NSData *data = [NSData dataWithBytes: &i length: sizeof(i)];   
//data 转int  
int i;   
[data getBytes: &i length: sizeof(i)];   

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部