Justin Chand
Justin Chand

Reputation: 43

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.

Upvotes: 1

Views: 7547

Answers (1)

samgak
samgak

Reputation: 24427

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].

Upvotes: 3

Related Questions