4

I am looking a way to 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.

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

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Nico
  • 374
  • 2
  • 4
  • 17

4 Answers4

3

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

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

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.

Community
  • 1
  • 1
gknicker
  • 5,509
  • 2
  • 25
  • 41
  • Thanks for your answer @gknicker but further the code i was trying to understand what must i do – Nico Jan 22 '15 at 13:55
  • Haha, I'm so happy that my long forgotten gist snippet has sneaked around to SO. And I just included a main test method for convenience in response to a comment in the gist file. – neuro_sys Oct 15 '15 at 19:46
  • This code produces a leading zero if the number of digits supplied it 3 or 5 or 7 and works well if the number is divided by 2. Does it need a leading zero? Why? Is there a version that produces BCD byte array without a leading zero regardless whether 3 or 4 digits are supplied as input? – InterestedDev Oct 19 '17 at 01:40
0

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

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

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

David Conrad
  • 15,432
  • 2
  • 42
  • 54
0

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, 16);
    }
    return binBcd;
}
BlueM
  • 6,523
  • 1
  • 25
  • 30
cahit beyaz
  • 4,829
  • 1
  • 30
  • 25
  • 1
    Your code is wrong. The result is not BCD. Byte.parseByte(sByte) does not parse hex but decimal. Byte.parseByte(sByte, 16) should fix it. – BlueM Aug 11 '21 at 09:18
0

You can try the following code to convert String to a byte array first:

public static byte[] hex2Bytes(String str) {
    byte[] b = new byte[str.length() / 2];
    int j = 0;
    for (int i = 0; i < b.length; i++) {
        char c0 = str.charAt(j++);
        char c1 = str.charAt(j++);
        b[i] = ((byte) (parse(c0) << 4 | parse(c1)));
    }
    return b;
}

private static int parse(char c) {
    if (c >= 'a')
        return c - 'a' + 10 & 0xF;
    if (c >= 'A')
        return c - 'A' + 10 & 0xF;
    return c - '0' & 0xF;
}

This is a method that converts a hexadecimal string to a byte array. It does this by looping through each pair of characters in the input string, parsing them as nibbles (half-bytes), and then combining them into a byte using bitwise operations. The resulting bytes are stored in an output byte array, which is returned by the method.

Zach Liu
  • 11
  • 2
  • 1
    Please avoid just giving an answer and provide proper explanation of your answer. – HaroldSer Nov 03 '21 at 07:54
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 03 '21 at 07:54