So currently I have an array of binary digits, say {1, 1, 1, 1, 0, 0, 0, 0} and I'm trying to figure out how I can convert this array into a hexadecimal digit of type 'uint8_t' in C (in this example, I would want it to be 0xf0) except I'm struggling to figure out how to do so. So far I've been able to convert the digit to hexadecimal string except I want it to be an unsigned integer type. Could anyone please provide me some suggestions? Thank you!
Asked
Active
Viewed 1,005 times
0
-
1What do you mean with convert to hex? once you [convert the binary format string to int](https://stackoverflow.com/questions/2343099/convert-binary-format-string-to-int-in-c) you can print this `int` (or `uint8_t` in your case) with `"%x"` which is the [format specifier for hex](https://stackoverflow.com/questions/14733761/printf-formatting-for-hex) – David Ranieri May 22 '20 at 06:45
1 Answers
1
Try this
#include <stdio.h>
#include <stdint.h>
uint16_t ConvertToDec(uint16_t* bits, uint16_t size)
{
uint16_t result = 0;
for (uint16_t i = 0; i < size; i++) {
result |= bits[i];
if(i != size-1)
result <<= 1;
}
return result;
}
int main()
{
uint16_t bits[] = { 1, 1, 1, 1, 0, 0, 0, 0 };
uint16_t len = (sizeof(bits) / sizeof(bits[0])); // get array size
uint16_t result = ConvertToDec(bits, len);
char hex[20];
sprintf(hex, "0x%02X", result);
printf("%s", hex);
return 0;
}
ConvertToDec converts the array into 8 bit number, and using sprintf saves the output as hex into the hex buffer. Edit : I have modified the code a little bit making it more readable and also to work with 16 bit numbers as well.
Best regards

spstrademark
- 445
- 2
- 5
- 22
-
Hello thank you for this! I have a few questions thought. First, why is it in the convert_to_dec function you have i < size - 1, as wouldn't this skip the last digit? Also, would this method happen to work for if the bit array was say, size = 4 instead? – user12345678 May 23 '20 at 05:40
-
@oliviah Hello first the -1 in the loop was because on the last cycle the 8th digit was lost, yes it can work with the size of 4 as well. I have modified the code a bit making it more readable and adding to work with 16 bit numbers as well. Kind regards! – spstrademark May 23 '20 at 07:37