Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary coded decimal (BCD) to Hexadecimal conversion

Tags:

hex

bcd

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

like image 508
iPadDevloperJr Avatar asked Dec 20 '10 22:12

iPadDevloperJr


4 Answers

BCD is a subset of hexadecimal, so there is no conversion necessary -- any given BCD value is identical to the corresponding hexadecimal value. For example, '98' in BCD is 10011000, which is the same as 98 in hexadecimal

like image 57
Chris Dodd Avatar answered Sep 30 '22 14:09

Chris Dodd


I don't quite understand your question, but I'm guessing that e.g. someone gives you a number 98 encoded in BCD, which would be:

1001 1000

and you are supposed to get:

62H

What I would propose:

1) convert BCD-encoded value to decimal value (D)

2) convert D to hexadecimal value.

Depending on which programming language you choose, this task will be easier or harder.

EDIT: In Java it could be:

    byte bcd = (byte)0x98; // BCD value: 1001 1000

    int decimal = (bcd & 0xF) + (((int)bcd & 0xF0) >> 4)*10;

    System.out.println(
            Integer.toHexString(decimal)
    );
like image 28
Lukasz Avatar answered Sep 30 '22 14:09

Lukasz


Go between different combinations of Hex, Decimal, and Binary. If you know how binary works then you should easily be able to use BCD:

Hex  Dec  BCD
0    0    0000
1    1    0001
2    2    0010
3    3    0011
4    4    0100
5    5    0101
6    6    0110
7    7    0111
8    8    1000
9    9    1001
A   10    0001 0000 <-- notice that each digit looks like hex except it can only go to 9.
B   11    0001 0001
C   12    0001 0010
D   13    0001 0011
E   14    0001 0100
F   15    0001 0101

Once you got this part of it down, you should be able to use divide by 10 or %10 to find any combination to generate your BCD. Since it only uses 10 combinations instead of all 16 you will lose some information.

like image 35
Cyber Slueth Omega Avatar answered Sep 30 '22 14:09

Cyber Slueth Omega


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; 
}
like image 25
Simon Peverett Avatar answered Sep 30 '22 13:09

Simon Peverett