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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28077671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 12:58:20  来源:igfitidea点击:

Algorithm to convert a String of decimal digits to BCD

javaarraysstringbcd

提问by Nico

I am looking a way for convert a string to BCD equivalent. I use java, but it is not a question of the language indeed. I am trying to understand step by step how to convert a string to BCD.

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

For example, suppose i have the following string;

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

"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)

In BCD (according this page: http://es.wikipedia.org/wiki/Decimal_codificado_en_binario):

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

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

Ok , i think the conversion is correct but i have to save this in a byte[2]. What Should i have to do? After, i have to read the BCD and convert it to the original string "0200" but first i have to resolve String to BCD.

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

Regards!

问候!

采纳答案by gknicker

Find a utility class to do this for you. Surely someone out there has written a BCD conversion utility for Java.

找到一个实用程序类来为您执行此操作。肯定有人为 Java 编写了 BCD 转换实用程序。

Here you go. I Googled "BCD Java" and got this as the first result. Copying code here for future reference.

干得好。我在谷歌上搜索了“BCD Java”并得到了第一个结果。在此处复制代码以供将来参考。

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();
    }
}

There's also this question: Java code or lib to decode a binary-coded decimal (BCD) from a String.

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

回答by Nico

This image help me a lot to understand my own example.

这张图片对我理解我自己的例子有很大帮助。

enter image description here

在此处输入图片说明

回答by kris

https://gist.github.com/neuro-sys/953548

https://gist.github.com/neuro-sys/953548

The link to the code of neuro-sys/BCDConvert.java

Neuro-sys/BCDConvert.java 代码链接

回答by cahit beyaz

You can use following:

您可以使用以下内容:

//Convert BCD String to byte array
public static byte[] String2Bcd(java.lang.String bcdString) {

    byte[] binBcd = new byte[bcdString.length() / 2];

    for (int i = 0; i < binBcd.length; i++) {
        String sByte = bcdString.substring(i*2, i*2+2);
        binBcd[i] = Byte.parseByte(sByte);
    }
    return binBcd;
}

回答by David Conrad

The first step would be to parse the string into an int so that you have the numeric value of it. Then, get the individual digits using division and modulus, and pack each pair of digits into a byte using shift and add (or shift and or).

第一步是将字符串解析为 int,以便获得它的数值。然后,使用除法和模数获取单个数字,并使用 shift 和 add(或 shift and or)将每对数字打包成一个字节。

Alternatively, you could parse each character of the string into an int individually, and avoid using division and modulus to get the numbers, but I would prefer to parse the entire string up front so that you discover right away if the string is invalid. (If you get a NumberFormatException, or if the value is less than 0 or greater than 9999 then it is invalid.)

或者,您可以将字符串的每个字符单独解析为 int,并避免使用除法和模数来获取数字,但我更愿意预先解析整个字符串,以便您立即发现字符串是否无效。(如果您收到 NumberFormatException,或者该值小于 0 或大于 9999,则它无效。)

Finally, once you have assembled the two individual bytes, you can put them into the byte[2].

最后,一旦您组装了两个单独的字节,就可以将它们放入 byte[2].