进制转换

2017-01-20  本文已影响27人  哎呦我去叫什么呢

//2进制转10进制

NSString转char
char mychar[string.length];
strcpy(mychar,(char *)[string UTF8String]);

    char ch = mychar[i];
   原文:http://www.cocoachina.com/bbs/read.php?tid=141348

/将十进制转化为二进制,设置返回NSString 长度

}

//将十进制转化为十六进制

-(NSString *)getBinaryByhex:(NSString *)hex
{
NSMutableDictionary *hexDic = [[NSMutableDictionary alloc] init];

hexDic = [[NSMutableDictionary alloc] initWithCapacity:16];
 
[hexDic setObject:@"0000" forKey:@"0"];
 
[hexDic setObject:@"0001" forKey:@"1"];
 
[hexDic setObject:@"0010" forKey:@"2"];
 
[hexDic setObject:@"0011" forKey:@"3"];
 
[hexDic setObject:@"0100" forKey:@"4"];
 
[hexDic setObject:@"0101" forKey:@"5"];
 
[hexDic setObject:@"0110" forKey:@"6"];
 
[hexDic setObject:@"0111" forKey:@"7"];
 
[hexDic setObject:@"1000" forKey:@"8"];
 
[hexDic setObject:@"1001" forKey:@"9"];
 
[hexDic setObject:@"1010" forKey:@"A"];
 
[hexDic setObject:@"1011" forKey:@"B"];
 
[hexDic setObject:@"1100" forKey:@"C"];
 
[hexDic setObject:@"1101" forKey:@"D"];
 
[hexDic setObject:@"1110" forKey:@"E"];
 
[hexDic setObject:@"1111" forKey:@"F"];
 
NSMutableString *binaryString=[[NSMutableString alloc] init];
 
for (int i=0; i<[hex length]; i++) {
     
    NSRange rage;
     
    rage.length = 1;
     
    rage.location = i;
     
    NSString *key = [hex substringWithRange:rage];
     
    //NSLog(@"%@",[NSString stringWithFormat:@"%@",[hexDic objectForKey:key]]);
     
    binaryString = [NSString stringWithFormat:@"%@%@",binaryString,[NSString stringWithFormat:@"%@",[hexDic objectForKey:key]]];
     
}
 
//NSLog(@"转化后的二进制为:%@",binaryString);
 
return binaryString;

}

上一篇 下一篇

猜你喜欢

热点阅读