The value used in my project is expressed with 4-bits binary coded decimals (BCD), which was originally stored in a character buffer (for example, pointed by a pointer const unsigned char *
). I want to convert the input BCD char stream to an integer. Would you please show me an efficient and fast way to do that?
Data format example and expected result:
BCD*2; 1001 0111 0110 0101=9765
"9" "7" "6" "5"
Thank you very much!
You can decipher the right-most digit like so:
const unsigned int bcdDigit = bcdNumber & 0xf;
then you can shift the number to the right, so that the next digit becomes the rightmost:
bcdNumber >>= 4;
This will give you the digits in the wrong order though (right to left). If you know how many digits you have, you can of course extract the proper bits directly.
Use e.g. (bcdNumber >> (4 * digitIndex)) & 0xf;
to extract the digitIndex
:th digit, where digit 0 is the rightmost.
unsigned int lulz(unsigned char const* nybbles, size_t length)
{
unsigned int result(0);
while (length--) {
result = result * 100 + (*nybbles >> 4) * 10 + (*nybbles & 15);
++nybbles;
}
return result;
}
length
here specifies the number of bytes in the input, so for the example given by the OP, nybbles
would be {0x97, 0x65}
and length
would be 2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With