- (NSString *)getHexByDecimal:(NSDecimalNumber *)decimal {
//10进制转换16进制(支持无穷大数)
NSString *hex =@"";
NSString *letter;
NSDecimalNumber *lastNumber = decimal;
for (int i = 0; i<999; i++) {
NSDecimalNumber *tempShang = [lastNumber decimalNumberByDividingBy:[NSDecimalNumber decimalNumberWithString:@"16"]];
NSString *tempShangString = [tempShang stringValue];
if ([tempShangString containsString:@"."]) {
// 有小数
tempShangString = [tempShangString substringToIndex:[tempShangString rangeOfString:@"."].location];
// DLog(@"%@", tempShangString);
NSDecimalNumber *number = [[NSDecimalNumber decimalNumberWithString:tempShangString] decimalNumberByMultiplyingBy:[NSDecimalNumber decimalNumberWithString:@"16"]];
NSDecimalNumber *yushu = [lastNumber decimalNumberBySubtracting:number];
int yushuInt = [[yushu stringValue] intValue];
switch (yushuInt) {
case 10:
letter =@"A"; break;
case 11:
letter =@"B"; break;
case 12:
letter =@"C"; break;
case 13:
letter =@"D"; break;
case 14:
letter =@"E"; break;
case 15:
letter =@"F"; break;
default:
letter = [NSString stringWithFormat:@"%d", yushuInt];
}
lastNumber = [NSDecimalNumber decimalNumberWithString:tempShangString];
} else {
// 没有小数
if (tempShangString.length <= 2 && [tempShangString intValue] < 16) {
int num = [tempShangString intValue];
if (num == 0) {
break;
}
switch (num) {
case 10:
letter =@"A"; break;
case 11:
letter =@"B"; break;
case 12:
letter =@"C"; break;
case 13:
letter =@"D"; break;
case 14:
letter =@"E"; break;
case 15:
letter =@"F"; break;
default:
letter = [NSString stringWithFormat:@"%d", num];
}
hex = [letter stringByAppendingString:hex];
break;
} else {
letter = @"0";
}
lastNumber = tempShang;
}
hex = [letter stringByAppendingString:hex];
}
// return hex;
return hex.length > 0 ? hex : @"0";
}
网友评论