簡體   English   中英

Java:在輸出中保留前導零

[英]Java: Retain leading zero in output

我有一個 Java 程序,它創建一個字節數組0x00 0x02 0x03 0x00 我將其轉換為BigInteger類型。 但是當我將它重新轉換為字節數組時,我得到的輸出沒有前導零2 3 0 以下是代碼:

byte[] b = new byte[] {0x00, 0x02, 0x03, 0x00};
BigInteger b1 = new BigInteger(b);
byte[] b2 = b1.toByteArray();

for (byte aB2 : b2) 
    System.out.print(aB2 + " ");

如何保留前導零?

謝謝。

你不能。 BigInteger不存儲該信息。

public BigInteger(byte[] val) {
    if (val.length == 0)
        throw new NumberFormatException("Zero length BigInteger");

    if (val[0] < 0) {
        mag = makePositive(val);
        signum = -1;
    } else {
        mag = stripLeadingZeroBytes(val);     // (!) <-- watch this
        signum = (mag.length == 0 ? 0 : 1);
    }
    if (mag.length >= MAX_MAG_LENGTH) {
        checkRange();
    }
}

如果您知道預期有多少字節,您可以很簡單地解決這個問題,只需將它們添加回輸出byte[]

在 Kotlin 中,這看起來像:

fun BigInteger.byteArrayPaddedToSize(size: Int): ByteArray {
    val byteArrayRepresentation = toByteArray().takeLast(size).toByteArray()
    return if (byteArrayRepresentation.size == size) {
        byteArrayRepresentation
    } else {
        val difference = size - byteArrayRepresentation.size
        ByteArray(difference) { 0x00 } + byteArrayRepresentation
    }
}

暫無
暫無

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

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