-2

For Objective-C:

Hi everyone, I'm trying to convert a hex input into binary. For example, someone enters in :

A55

I want that to convert to

101001010101

I've tried looking through past posts and none seem to be working for me. Any help would be greatly appreciated.

Sebastian
  • 7,670
  • 5
  • 38
  • 50
Abushawish
  • 1,466
  • 3
  • 20
  • 35

3 Answers3

3

Use a lookup table: there are only 16 possible characters in a HEX representation, each corresponding to a four-character binary code group. Go through the HEX character-by-character, obtain a lookup, and put it in the resultant NSString.

Here is a copy of the lookup table for you.

0 0000
1 0001
2 0010
3 0011
4 0100
5 0101
6 0110
7 0111
8 1000
9 1001
A 1010
B 1011
C 1100
D 1101
E 1110
F 1111

There are multiple options as to how to do lookups. The simplest way would be making a 128-element array, and placing NSStrings at the elements corresponding to codes of the characters (i.e. at positions '0', '1', ..., 'E', 'F', with single quotes; these are very important).

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

I believe there is a built-in function for this. If not, you should at least be able to go hex->dec then dec->bin

You can write the conversion from scratch if you know the number of characters, bin to hex is common enough algorithmically.

Community
  • 1
  • 1
Eric G
  • 907
  • 1
  • 9
  • 30
0

Build a lookup table (an array where you can supply a value between 0 and 15 to get the binary for that hex digit):

char *hex_to_bin[] = {
    "0000", "0001", "0010", "0011",
    /* ... */
    "1100", "1101", "1110", "1111"
};

There should be 16 elements in that table. The conversion process for multiple digits is to handle one digit at a time, appending the results onto the end of your result storage.

Use getchar() to read a char:

int c = getchar();
if (c < 0) { puts("Error: Invalid input or premature closure."); }

Use strchr() to determine which array index to retrieve:

char *digits = "00112233445566778899AaBbCcDdEeFf";
size_t digit = (strchr(digits, c) - digits) / 2;

Look up the corresponding binary values for digit:

printf("%s", hex_to_bin[digit]); // You'll want to use strcat here.
autistic
  • 1
  • 3
  • 35
  • 80