Decimal To Hexadecimal


More Conversions



Example Code

NSString *string = @"F";

/* Hex to Decimal */
NSLog(@"Decimal Value for Hex String %@ is %llu",string ,(UInt64)strtoull([string UTF8String], NULL, 16));

/* Hex to Octal */
NSLog(@"Octal Value for Hex String %@ is %llO",string ,(UInt64)strtoull([string UTF8String], NULL, 16));

/* Hex to Binary */
NSMutableString *hexString = [NSMutableString string];
for(int i = 0; i < [string length]; i++) {
    char c = [[string lowercaseString] characterAtIndex:i];
    switch(c) {
        case '0': [hexString appendString:@"0000"]; break;
        case '1': [hexString appendString:@"0001"]; break;
        case '2': [hexString appendString:@"0010"]; break;
        case '3': [hexString appendString:@"0011"]; break;
        case '4': [hexString appendString:@"0100"]; break;
        case '5': [hexString appendString:@"0101"]; break;
        case '6': [hexString appendString:@"0110"]; break;
        case '7': [hexString appendString:@"0111"]; break;
        case '8': [hexString appendString:@"1000"]; break;
        case '9': [hexString appendString:@"1001"]; break;
        case 'a': [hexString appendString:@"1010"]; break;
        case 'b': [hexString appendString:@"1011"]; break;
        case 'c': [hexString appendString:@"1100"]; break;
        case 'd': [hexString appendString:@"1101"]; break;
        case 'e': [hexString appendString:@"1110"]; break;
        case 'f': [hexString appendString:@"1111"]; break;
        default : break;
    }
}
NSLog(@"Binary Value for Hex String %@ is %@",string ,hexString);

var string = "F"

/* Hex to Decimal */
var decimalString = String(Int(string, radix: 16)!, radix: 10)
print("Decimal Value for Hex String \(string) is ",decimalString)

/* Hex to Octal */
var octalString = String(Int(string, radix: 16)!, radix: 8)
print("Octal Value for Hex String \(string) is ",octalString)

/* Hex to Binary */
var binaryString = String(Int(string, radix: 16)!, radix: 2)
print("Binary Value for Hex String \(string) is ",binaryString)

Result

Decimal Value for Hex String F is  15
Octal Value for Hex String F is  17
Binary Value for Hex String F is  1111

Advertisements