簡體   English   中英

(JAVA)將十進制轉換為二進制編碼的十進制?

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

例如,我想將 int 值12轉換為 BCD 的 String 輸出: 00 12 (0x00 0x12)。 如果我的 int 值為256 ,它將是02 56 (即 0x02 0x56),或者如果我的 int 值為999 ,它將是09 99 (0x09 0x99), 9999將是99 99 (0x99 0x99)。

現在,我唯一的解決方案是創建一個大小為 4 的 String 數組,並通過將 int 值轉換為 String 來計算那里有多少個字符。 如果有 2 個字符,我將在添加 2 個字符之前先將 2 x 0 添加到數組中,然后將它們重新轉換為單個 String 變量。

基本上,

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

如果有 3 個字符,我會先在數組中添加一個0 ,然后再添加 3 個字符。 我想知道有沒有其他方法?

這就是你要求的嗎?

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

並傳遞像

formatTheString(Integer.toString(256),4);

您可以使用String.format附加前導0並使用子字符串分成兩部分。

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

如果長度小於 4 String.format("%04d",value)將在前面附加0 s。

如果您不想使用子字符串,您可以使用如下所示的 String.split 和 String.join。

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

output.split("(?<=\\\\G.{2})")將每個字符串分成 2 個字符。

我認為你問的是不正確的。 請參閱BCD。

下面的代碼足以滿足您的需要

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

在上面的代碼中,n 是您的號碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM