AVR: Binary to BCD and vice versa

unsigned int bcd2i(unsigned int bcd) {
    unsigned int decimalMultiplier = 1;
    unsigned int digit;
    unsigned int i = 0;
    while (bcd > 0) {
        digit = bcd & 0xF;
        i += digit * decimalMultiplier;
        decimalMultiplier *= 10;
        bcd >>= 4;
    }
    return i;
}
unsigned int i2bcd(unsigned int i) {
    unsigned int binaryShift = 0;
    unsigned int digit;
    unsigned int bcd = 0;
    while (i > 0) {
        digit = i % 10;
        bcd += (digit << binaryShift);
        binaryShift += 4;
        i /= 10;
    }
    return bcd;
}

How to convert binary to BCD ?

1 thought on “AVR: Binary to BCD and vice versa

Leave a Reply to Nikola Cancel reply

Your email address will not be published. Required fields are marked *