1

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.

7
  • What do you mean by "best"? Fastest? Simplest code? Commented Oct 14, 2016 at 10:34
  • @samgak Sorry, simplest without being terribly poor performance wise. Not too worried about performance. Thanks Commented Oct 14, 2016 at 10:40
  • Your question is too broad and is not on topic. StackOverflow is not a coding service. Commented Oct 14, 2016 at 10:55
  • @2501 As someone new to C I was really interested in whether there's something built in to make this easier, as opposed to writing my own function. Thanks for your opinion though Commented Oct 14, 2016 at 10:58
  • convert binary string to int with atoi with base 2 and then int to hex string with sprintf Commented Oct 14, 2016 at 11:01

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.