0

For example, I would like to convert the int value 12 into a String output of BCD: 00 12 (0x00 0x12). If I have int value of 256, it will be 02 56 (which is 0x02 0x56), or if I have a int value of 999, it will be 09 99 (0x09 0x99), 9999 would be 99 99 (0x99 0x99).

Right now, my only solution is to create a String array of size 4, and calculate how many characters are there by converting the int value into String. If there are 2 characters, I will add 2 x 0 into the array first before adding the 2 characters, and then make them back into a single String variable.

Basically,

int value = 12;
String output = Integer.toString(value); 
// then count the number of characters in the String.
// 4 minus (whatever number of characters in the String, add zeros
// add the characters:
stringArray[0] = "0";
stringArray[1] = "0";
stringArray[2] = "1";
stringArray[3] = "2";
// then, concatenate them back

If there are 3 characters, I will add one 0 into the array first before adding 3 characters. I was wondering if there is any other way?

  • Just to clarify, that you wish to create an array of strings, each one containing a single-character string? – Martin Dec 10 '19 at 07:28
  • @Martin Hmm, I have an int value and I want to convert them into Binary-coded decimal(?) like an int value of 48 will become String value of "00 48" (0x00 0x48), and int value of 128 will become String value of "01 28" (0x01 0x28).. –  Dec 10 '19 at 07:33
  • This is *binary* to BCD conversion. No decimal input whatsoever. – user207421 Dec 10 '19 at 09:05

3 Answers3

0

You can use String.format to append leading 0 and use substring to split in to two part.

int value = 12;
String output = String.format("%04d",value);
System.out.println(output.substring(0,2)+" "+output.substring(2,4));

String.format("%04d",value) will append 0s in the front if the length is less than 4.

If you do not want to use substring you can use String.split and String.join like below.

System.out.println(
        String.join(
                " ",
                Arrays.asList(
                        output.split("(?<=\\G.{2})")
                )
        )
);

output.split("(?<=\\G.{2})") will split the string in 2 characters each.

seenukarthi
  • 8,241
  • 10
  • 47
  • 68
-1

Is that what you are asking for?

public static String formatTheString(String string, int length) {
    return String.format("%"+length+"s", string).replace(' ', '0');
}

and pass the values like

formatTheString(Integer.toString(256),4);
Confuser
  • 71
  • 1
  • 11
-1

I think what you are asking is not correct. refer this for BCD.

and below code is sufficient for what you need

System.out.printf("%04d",n);

in above code n is your number.