I put in this code which does what it's supposed to do, but perhaps there is a better or more general approach? I'm converting a 4-digit base 10 number e.g. "11" to base 16 e.g. "17" (which gets written out on the display as 11 when called with 17 because the function takes bits as argument).

    int hex1 = perhapsprime / 1000;
    int hex2 = (perhapsprime - hex1*1000) / 100;
    int hex3 = (perhapsprime - hex2*100 -hex1*1000) / 10;
    int hex4 = perhapsprime - hex3*10 - hex2*100 - hex1*1000;
    int test = 16*16*16*hex1+16*16*hex2+16*hex3+hex4;

The integer "test" will have the correct value after this code was run, but is there a more efficient way to do it?


I settled for the following that appears to be able to convert any number of digits to BCD:

int tbcd(int v) {
    int total = 0;
    int resultbase = 1;
    while(v > 0) {
        total += resultbase * (v % 10);
        resultbase *= 16;
        v /= 10;
    return total;

1 Answer 1


This is not a conversion to base 16. This is a conversion to BCD: Binary Coded Decimal. You are taking a (presumed) 4 digit decimal number and placing each decimal digit into its own 4 bit hexadecimal digit.

This is a perfectly legitimate thing to do, once you give it the right name. This may also help: http://en.wikipedia.org/wiki/Binary-coded_decimal.

Yes, there are much more general and less error-prone ways to convert integers into BCD. See https://stackoverflow.com/questions/1408361/decimal-to-bcd-conversion.

  • 1
    Thanks. I updated my question with a function that seems good. Mar 30, 2014 at 7:56
  • Looks good to me. +1 for providing code for others to use.
    – david.pfx
    Mar 30, 2014 at 8:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.