Binary coded decimal (BCD) to Hexadecimal conversion

前端 未结 5 1610
攒了一身酷
攒了一身酷 2021-01-12 02:47

can someone explain to me how to convert BCD to Hexadecimal? For example how can i convert 98(BCD) to Hexadecimal. Thanks.

5条回答
  •  無奈伤痛
    2021-01-12 03:03

    For any BCD encoded value (that will fit in an int).

    Iterative:

    unsigned int bcd2dec(unsigned int bcd)
    {
        unsigned int dec=0;
        unsigned int mult;
        for (mult=1; bcd; bcd=bcd>>4,mult*=10)
        {
            dec += (bcd & 0x0f) * mult;
        }
        return dec;
    }
    

    Recursive:

    unsigned int bcd2dec_r(unsigned int bcd)
    {
        return bcd ? (bcd2dec_r(bcd>>4)*10) + (bcd & 0x0f) : 0; 
    }
    

提交回复
热议问题