So I'm trying to figure out how I can convert a binary array (of either size of 4 or 8) to a decimal and hexadecimal number in C.
E.g. say you had {0, 0, 0, 1} or {1, 1, 1, 1, 0, 0, 0, 0} and you want to convert to decimal and hexadecimal. I managed to get it working through using the 8 binary array through this link, however my method seems to fall when I try to use it for 4 element.
uint8_t ConvertToDec(uint8_t * bits, uint8_t size)
{
uint8_t result = 0 ;
for(uint8_t i=0; i < size-1; i++ ){
result |=bits[i];
result<<=1;
}
return result;
}
int main()
{
uint8_t bits[] = {1, 1, 1, 1, 0, 0, 0, 0};
uint8_t len = (sizeof(bits)/sizeof(bits[0]));
uint8_t result = ConvertToDec(bits,len);
char hex[5];
sprintf(hex,"0x%02X",result);
printf("%s",hex);
return 0;
}