Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decode binary coded decimal (BCD) to unsigned integer

Tags:

c++

bcd

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!

like image 640
Golden Lee Avatar asked May 26 '11 11:05

Golden Lee


2 Answers

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.

like image 29
unwind Avatar answered Sep 30 '22 14:09

unwind


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.

like image 155
Chris Jester-Young Avatar answered Sep 30 '22 13:09

Chris Jester-Young