简体   繁体   English

如何将 BCD 转换为十进制,反之亦然?

[英]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

Explanation解释

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 ,它确实在高半字节中有一个40100b )和一个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.

相关问题 如何在jquery或javascript和PHP中将GPS度转换为十进制,反之亦然? - How to convert GPS degree to decimal and vice-versa in jquery or javascript and PHP? 在 vanilla javascript 中将十进制转换为有符号 2 的恭维,反之亦然 - convert Decimal to signed 2's compliment and vice versa in vanilla javascript 如何将数组转换为矩阵,反之亦然? - How to convert an array to a matrix and vice versa? 如何将JavaScript日期作为“本地时间”提取,然后将其转换为UTC,反之亦然? - How to ingest javascript date as 'local time' then convert it to UTC and vice versa? 如何在javascript中将整数数组转换为十六进制字符串,反之亦然 - how to convert array of integers into hex string and vice versa in javascript 如何将 Firestore 文档转换为普通 json,反之亦然 - How to convert a Firestore Document to plain json and vice versa 将ArrayBuffer转换为Array,反之亦然 - Convert ArrayBuffer to Array and vice-versa 将大整数转换为字节数组,反之亦然 - Convert big integer to byte array and vice versa 在JavaScript中将字符串转换为整数数组,反之亦然 - Convert string to array of integers and vice versa in JavaScript 将JS var转换为PHP,反之亦然 - convert JS var to PHP and vice versa
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM