I am trying to write code in JavaScript to convert binary-coded decimal into decimal and vice-versa.
How can I achieve this?
I am trying to write code in JavaScript to convert binary-coded decimal into decimal and vice-versa.
How can I achieve this?
To encode and decode values using Binary Coded Decimal (BCD):
dec2bcd = dec => parseInt(dec.toString(10),16);
bcd2dec = bcd => parseInt(bcd.toString(16),10);
console.log(dec2bcd(42)); // 66 (0x42)
console.log(bcd2dec(66)); // 42
Suppose you have the number 42. To encode this as binary coded decimal, you place '4' in the high nibble and a '2' in the low nibble. The most straightforward way of doing this is to reinterpret the string representation of the decimal number as hex. So convert the value 42
to the string '42'
and then parse this as hex to arrive at the number 66
, which, if you examine it in binary is 01000010b
, which indeed has a 4
(0100b
) in the high nibble and a 2
(0010b
) in the low nibble.
To decode, just format the number as a string using hexadecimal encoding, and then reinterpret this string as decimal.