Decode Binary Coded Decimal (BCD) for unsigned integers

The value used in my project is expressed by four binary coded decimal places (BCDs) that were originally stored in the character buffer (for example, indicated by the const unsigned char * pointer). I want to convert BCD char input stream to integer. Could you show me an efficient and quick way to do this?

Example data format and expected result:

 BCD*2; 1001 0111 0110 0101=9765 "9" "7" "6" "5" 

Many thanks!

+6
source share
2 answers
 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 indicates the number of bytes in the input, so for the example given by OP, nybbles will be {0x97, 0x65} , and length will be 2.

+7
source

You can decrypt the right digit as follows:

 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 numbers in the wrong order though (from right to left). If you know how many digits you have, you can, of course, directly extract the correct bits.

Use for example. (bcdNumber >> (4 * digitIndex)) & 0xf; to extract the digit digitIndex : th, where the digit 0 is the digitIndex .

+5
source

Source: https://habr.com/ru/post/889105/


All Articles