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.

7
  • 1
    You can extend your array by 8-currentSize elements with value = 0 on the left side Commented Jul 11, 2013 at 7:42
  • 2
    Provide example of binStr and expected output? Commented Jul 11, 2013 at 7:43
  • 1
    @anubhava It's implied by OP's line of code: binStr = "0011010111...11"; array = {120, -145, ..., 20}. Commented Jul 11, 2013 at 7:52
  • 6
    You still can't store 160 bits in 8 bytes - you need 20 bytes. Commented Jul 11, 2013 at 7:52
  • You could use System.arraycopy to copy to copy to 8 byte array Commented Jul 11, 2013 at 7:57

2 Answers 2

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; } 
Sign up to request clarification or add additional context in comments.

Comments

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] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.