Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon.

Pages: 1-

Converting BCD to binary and vice-versa

Name: OP, obviously 2011-02-13 11:12

Is there any better way to do this?

unsigned int bin2bcd(unsigned int bin) {
    unsigned int result;
    for (result = 0; bin > 0; bin /= 10) {
        result = (result << 4) + (bin % 10);
    }
    return result;
}

unsigned int bcd2bin(unsigned int bcd) {
    unsigned int i, result;
    for (result = 0, i = 1; bcd > 0; bcd >>= 4, i *= 10) {
        result += (bcd & 0x0f) * i;
    }
    return result;
}

Name: Anonymous 2011-02-13 11:15

x86 asm has specialized instructions for dealing with BCD numbers.

Name: Anonymous 2011-02-13 11:17

>>2
A good compiler should optimize it for you.

Name: Anonymous 2011-02-13 11:26

>>2
x86_64 doesn't. But answer to OP question is simple.


USE LOOKUP TABLES

Name: Anonymous 2011-02-13 12:36

Lookup tables are pig disgusting

Name: Anonymous 2011-02-13 12:51

>>5
They are quite elegant, actually. Even more elegant if you can generate them at compile-time within your code.

Name: Anonymous 2011-02-13 13:01

>>6
Like in Lisp, or glorious D.

Name: Anonymous 2011-02-13 15:20

>>7
I like the way you think.

Name: Anonymous 2011-02-13 16:29

3210 GET

Don't change these.
Name: Email:
Entire Thread Thread List