你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> iOS中NSString轉換成HEX(十六進制)-NSData轉換成int

iOS中NSString轉換成HEX(十六進制)-NSData轉換成int

編輯:IOS開發綜合

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 { // 
 
char *myBuffer = (char *)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)]; 


  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved