Reputation: 45
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!
Upvotes: 0
Views: 1484
Reputation: 475
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
Upvotes: 1