[英]How to convert BCD to decimal and vice versa?
I am trying to write code in JavaScript to convert binary-coded decimal into decimal and vice-versa.我正在尝试在 JavaScript 中编写代码,将二进制编码的十进制转换为十进制,反之亦然。
How can I achieve this?我怎样才能做到这一点?
To encode and decode values using Binary Coded Decimal (BCD):要使用二进制编码十进制(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.假设您有数字 42。要将其编码为二进制编码的十进制,您将“4”放在高半字节,将“2”放在低半字节。 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.因此,将值
42
转换为字符串'42'
,然后将其解析为十六进制以得到数字66
,如果你以二进制形式检查它,它是01000010b
,它确实在高半字节中有一个4
( 0100b
)和一个2
( 0010b
) 在低半字节。
To decode, just format the number as a string using hexadecimal encoding, and then reinterpret this string as decimal.要解码,只需使用十六进制编码将数字格式化为字符串,然后将此字符串重新解释为十进制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.