Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Hex to Binary iphone

I need to convert a hex string to binary form in objective-c, Could someone please guide me? For example if i have a hex string 7fefff78, i want to convert it to 1111111111011111111111101111000?

BR, Suppi

like image 923
Suppi Avatar asked Aug 25 '11 17:08

Suppi


People also ask

How do you change hex to binary?

Hexadecimal to binarySplit the hex number into individual values. Convert each hex value into its decimal equivalent. Next, convert each decimal digit into binary, making sure to write four digits for each value. Combine all four digits to make one binary number.

What is hex in binary?

Hexadecimal (or hex) is a base 16 system used to simplify how binary is represented. A hex digit can be any of the following 16 digits: 0 1 2 3 4 5 6 7 8 9 A B C D E F. Each hex digit reflects a 4-bit binary sequence.


2 Answers

Nice recursive solution...

NSString *hex = @"49cf3e";
NSUInteger hexAsInt;
[[NSScanner scannerWithString:hex] scanHexInt:&hexAsInt];
NSString *binary = [NSString stringWithFormat:@"%@", [self toBinary:hexAsInt]];

-(NSString *)toBinary:(NSUInteger)input
{
    if (input == 1 || input == 0)
        return [NSString stringWithFormat:@"%u", input];
    return [NSString stringWithFormat:@"%@%u", [self toBinary:input / 2], input % 2];
}
like image 143
Mundi Avatar answered Nov 10 '22 11:11

Mundi


Simply convert each digit one by one: 0 -> 0000, 7 -> 0111, F -> 1111, etc. A little lookup table could make this very concise.

The beauty of number bases that are powers of another base :-)

like image 39
Kerrek SB Avatar answered Nov 10 '22 11:11

Kerrek SB