简体   繁体   English

(JAVA)将十进制转换为二进制编码的十进制?

[英](JAVA) convert decimal to Binary coded decimal?

For example, I would like to convert the int value 12 into a String output of BCD: 00 12 (0x00 0x12).例如,我想将 int 值12转换为 BCD 的 String 输出: 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).如果我的 int 值为256 ,它将是02 56 (即 0x02 0x56),或者如果我的 int 值为999 ,它将是09 99 (0x09 0x99), 9999将是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.现在,我唯一的解决方案是创建一个大小为 4 的 String 数组,并通过将 int 值转换为 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.如果有 2 个字符,我将在添加 2 个字符之前先将 2 x 0 添加到数组中,然后将它们重新转换为单个 String 变量。

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.如果有 3 个字符,我会先在数组中添加一个0 ,然后再添加 3 个字符。 I was wondering if there is any other way?我想知道有没有其他方法?

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

You can use String.format to append leading 0 and use substring to split in to two part.您可以使用String.format附加前导0并使用子字符串分成两部分。

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 0 s in the front if the length is less than 4.如果长度小于 4 String.format("%04d",value)将在前面附加0 s。

If you do not want to use substring you can use String.split and String.join like below.如果您不想使用子字符串,您可以使用如下所示的 String.split 和 String.join。

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

output.split("(?<=\\\\G.{2})") will split the string in 2 characters each. output.split("(?<=\\\\G.{2})")将每个字符串分成 2 个字符。

I think what you are asking is not correct.我认为你问的是不正确的。 refer this for BCD.请参阅BCD。

and below code is sufficient for what you need下面的代码足以满足您的需要

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

in above code n is your number.在上面的代码中,n 是您的号码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM