iOS 将十进制转化为十六进制、十进制转二进制

时间:2021-09-09 20:56:40

//将十进制转化为十六进制
- (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;}

//十进制转二进制
- (NSString *)toBinarySystemWithDecimalSystem:(NSInteger)decimal
{
NSInteger num = decimal;//[decimal intValue];
NSInteger remainder = 0; //余数
NSInteger divisor = 0; //除数
NSString * prepare = @”“;

while (true)
{
remainder = num%2;
divisor = num/2;
num = divisor;
prepare = [prepare stringByAppendingFormat:@”%ld”,remainder];

if (divisor == 0)
{
break;
}
}

NSString * result = @”“;
for (NSInteger i = prepare.length - 1; i >= 0; i –)
{
result = [result stringByAppendingFormat:@”%@”,
[prepare substringWithRange:NSMakeRange(i , 1)]];
}

return result;
}