Justin Chand Justin Chand - 1 month ago 11
C Question

Convert binary string to hexadecimal string C

As the title said I was interested in the best way to convert a binary string to a hexadecimal string in C. The binary string is 4 bits at most so converting into a single hexadecimal char would be best.

Thanks for any help, I'm not sure if there's something built in to make this easier so don't have my own attempt to post yet.

Answer

You can use strtol to convert the binary string to an integer, and then sprintf to convert the integer to a hex string:

char* binaryString = "1101";

// convert binary string to integer
int value = (int)strtol(binaryString, NULL, 2);

// convert integer to hex string
char hexString[12]; // long enough for any 32-bit value, 4-byte aligned
sprintf(hexString, "%x", value);

// output hex string
printf(hexString);

Output:

d

If it's guaranteed to be a single hexadecimal character just take hexString[0].