gpt4 book ai didi

java - 将一串十进制数字转换为 BCD 的算法

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:09:21 30 4
gpt4 key购买 nike

我正在寻找一种将字符串转换为等效 BCD 码的方法。我使用Java,但这确实不是语言的问题。我试图逐步了解如何将字符串转换为 BCD。

例如,假设我有以下字符串;

"0200" (This string has four ASCII characters, if we were in java this string had been contained in a byte[4] where byte[0] = 48, byte[1] = 50, byte[2] = 48 and byte[3] = 48)

在 BCD 中(根据本页:http://es.wikipedia.org/wiki/Decimal_codificado_en_binario):

0 = 0000
2 = 0010
0 = 0000
0 = 0000

好的,我认为转换是正确的,但我必须将其保存在字节 [2] 中。我应该做什么?之后,我必须读取 BCD 并将其转换为原始字符串“0200”,但首先我必须将字符串解析为 BCD。

最佳答案

找一个实用类来为你做这件事。肯定有人已经为 Java 编写了 BCD 转换实用程序。

给你。我用谷歌搜索“BCD Java”并得到了this as the first result .在此处复制代码以供将来引用。

public class BCD {

/*
* long number to bcd byte array e.g. 123 --> (0000) 0001 0010 0011
* e.g. 12 ---> 0001 0010
*/
public static byte[] DecToBCDArray(long num) {
int digits = 0;

long temp = num;
while (temp != 0) {
digits++;
temp /= 10;
}

int byteLen = digits % 2 == 0 ? digits / 2 : (digits + 1) / 2;
boolean isOdd = digits % 2 != 0;

byte bcd[] = new byte[byteLen];

for (int i = 0; i < digits; i++) {
byte tmp = (byte) (num % 10);

if (i == digits - 1 && isOdd)
bcd[i / 2] = tmp;
else if (i % 2 == 0)
bcd[i / 2] = tmp;
else {
byte foo = (byte) (tmp << 4);
bcd[i / 2] |= foo;
}

num /= 10;
}

for (int i = 0; i < byteLen / 2; i++) {
byte tmp = bcd[i];
bcd[i] = bcd[byteLen - i - 1];
bcd[byteLen - i - 1] = tmp;
}

return bcd;
}

public static String BCDtoString(byte bcd) {
StringBuffer sb = new StringBuffer();

byte high = (byte) (bcd & 0xf0);
high >>>= (byte) 4;
high = (byte) (high & 0x0f);
byte low = (byte) (bcd & 0x0f);

sb.append(high);
sb.append(low);

return sb.toString();
}

public static String BCDtoString(byte[] bcd) {

StringBuffer sb = new StringBuffer();

for (int i = 0; i < bcd.length; i++) {
sb.append(BCDtoString(bcd[i]));
}

return sb.toString();
}
}

还有这个问题:Java code or lib to decode a binary-coded decimal (BCD) from a String .

关于java - 将一串十进制数字转换为 BCD 的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28077671/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com