首先 16进制的 16个数字应该是 0-9 A(10),B(11),C(12),D(13),E(14),F (15)余数大于9的时候应该转换为ABCDEF
算法是 ,用10进制数字(即46323)除以16,一直除下去,直至不能再做除法时止
第一次商2895余3
第二次商180余15
第三次商11余4
至此为止将最后的商和之前的余数11 4 15 3 倒写回去3 15 4 11
即 在16进制中即B4F3
再举个例子
100转换为16进制:100/16=6余4 6/16余6 余数倒着看回去 转换为16进制为 64
//——————————————将十进制转化为十六进制—————————————
- (NSString *)ToHex:(uint16_t)tmpid{
NSString *nLetterValue;
NSString *str =@"";
uint16_t ttmpig;
for (int i = 0; i<9; i++) {
ttmpig=tmpid%16;
tmpid=tmpid/16;
switch (ttmpig)
{
case 10:
nLetterValue =@"A";break;
case 11:
nLetterValue =@"B";break;
case 12:
nLetterValue =@"C";break;
case 13:
nLetterValue =@"D";break;
case 14:
nLetterValue =@"E";break;
case 15:
nLetterValue =@"F";break;
default:
nLetterValue = [NSString stringWithFormat:@"%u",ttmpig];
}
str = [nLetterValue stringByAppendingString:str];
if (tmpid == 0) {
break;
}
}
return str;
}
//————————iOS 十六进制字符串 转 十进制 ————————————
UInt64 mac1 = strtoul([@"abcd1234" UTF8String], 0, 16);
如果在有溢出,使用下面方法:
unsigned long long result = 0;
NSScanner *scanner = [NSScanner scannerWithString:@"abcd12345678"];
[scanner scanHexLongLong:&result];
如:a3b8e5 即表示:RGB red:163 green:184 blue:229.
那么怎样从 @“a3b8e5”中得到上面的结果?
有一个非常有用的函数:strtoul
int red = strtoul([[@“a3b8e5” substringWithRange:NSMakeRange(0, 2)] UTF8String],0,16);
int green = strtoul([[@“a3b8e5” substringWithRange:NSMakeRange(2, 2)] UTF8String],0,16);
int blue = strtoul([[@“a3b8e5” substringWithRange:NSMakeRange(4, 2)] UTF8String],0,16);
//————————————————————————————NSString 转成16进制NSData————————————————————————————
- -(NSData*)stringToByte:(NSString*)string
- {
- NSString *hexString=[[string uppercaseString] stringByReplacingOccurrencesOfString:@" " withString:@""];
- if ([hexString length]%2!=0) {
- return nil;
- }
- Byte tempbyt[1]={0};
- NSMutableData* bytes=[NSMutableData data];
- for(int i=0;i<[hexString length];i++)
- {
- 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
- return nil;
- 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_char2 >= 'A' && hex_char2 <='F')
- int_ch2 = hex_char2-55; A 的Ascll - 65
- else
- return nil;
- tempbyt[0] = int_ch1+int_ch2; ///将转化后的数放入Byte数组里
- [bytes appendBytes:tempbyt length:1];
- }
- return bytes;
- }