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
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.
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.
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];
}
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 :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With