1

I have a binary string containing 160 digit. I have tried:

new BigInteger("0000000000000000000000000000000000000000000000010000000000000000000000000000001000000000010000011010000000000000000000000000000000000000000000000000000000000000", 2).toByteArray()

but it returns the 15 bytes array with removed leading 0 bytes.

I would like reserve those leading 0 bytes, keep it 20 bytes.

I know some other ways to accomplish that, but I would like to know is there any easier way might just need few lines of code.

Arst
  • 3,098
  • 1
  • 35
  • 42

2 Answers2

1

Why not simply:

public static byte[] convert160bitsToBytes(String binStr) {
    byte[] a = new BigInteger(binStr, 2).toByteArray();
    byte[] b = new byte[20];
    int i = 20 - a.length;
    int j = 0;
    if (i < 0) throw new IllegalArgumentException("string was too long");
    for (; j < a.length; j++,i++) {
        b[i] = a[j];
    }
    return b;
}
Ingo
  • 36,037
  • 5
  • 53
  • 100
1

Something like this code should work for you:

byte[] src = new BigInteger(binStr, 2).toByteArray();
byte[] dest = new byte[(binStr.length()+7)/8]; // 20 bytes long for String of 160 length
System.arraycopy(src, 0, dest, 20 - src.length, src.length);
// testing
System.out.printf("Bytes: %d:%s%n", dest.length, Arrays.toString(dest));

OUTPUT:

Bytes: 20:[0, 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 65, -96, 0, 0, 0, 0, 0, 0, 0]
anubhava
  • 761,203
  • 64
  • 569
  • 643