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!
1 Answer
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
2 Comments
user12345678
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?
spstrademark
@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!
int(oruint8_tin your case) with"%x"which is the format specifier for hex