Binary coded decimal (BCD) to Hexadecimal conversion
can someone explain to me how to convert BCD to开发者_StackOverflow中文版 Hexadecimal? For example how can i convert 98(BCD) to Hexadecimal. Thanks.
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)
);
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
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;
}
I'd create a table of 256 entries, mapping all BCD bytes into their binary equivalent; you can then use hex printing of your programming language.
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.
精彩评论