Decode binary coded decimal (BCD) to unsigned integer

Golden Lee picture Golden Lee · May 26, 2011 · Viewed 15.7k times · Source

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!

Answer

Chris Jester-Young picture Chris Jester-Young · May 26, 2011
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.