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

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 12:51

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

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