Java:保留输出中的前导零

时间:2016-11-19 16:50:11

标签: java rsa padding

我有一个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 + " ");

如何保留前导零?

感谢。

2 个答案:

答案 0 :(得分:4)

你做不到。 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();
    }
}

答案 1 :(得分:0)

如果您知道预期有多少字节,您可以非常简单地解决这个问题,只需将它们添加回输出 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
    }
}
相关问题