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.
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; // long enough for any 32-bit value, 4-byte aligned sprintf(hexString, "%x", value); // output hex string printf(hexString);
If it's guaranteed to be a single hexadecimal character just take