4

Can anyone explain me why when I constructing BigInteger with 2 byte value toByteArray() then returns 3.

BigInteger data = new BigInteger("FFFF", 16))
data.toByteArray() <-- here am getting 3 bytes.

I think this is because BIgInteger signed by default. Is there any work-around for this?

Also, why BigInteger stores 1 byte value without two's complement additional byte? I am just trying to figure out one elegant way to process all my values.

Constantine
  • 1,802
  • 3
  • 23
  • 37
  • 5
    Did you read [the Javadoc](https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#toByteArray())? That explains the length: it needs the extra byte for the sign bit. – Andy Turner Nov 21 '16 at 23:15
  • 5
    `FFFF` in base 16 is the *positive* number 65535. [`toByteArray()`](https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html#toByteArray--) returns a [two's complement](https://en.wikipedia.org/wiki/Two's_complement) value, so it has to return the bytes `00 FF FF`, because the two's complement of bytes `FF FF` is -1, not 65535. It is in the definition and only work-around is to manually remove leading `00` byte if you want to interpret result as unsigned. – Andreas Nov 21 '16 at 23:19
  • Ok, there is signum flag in constructor from byte[]. Are there way to make same thing with string? – Constantine Nov 21 '16 at 23:23
  • I think this is a duplicate of this question: http://stackoverflow.com/questions/4407779/biginteger-to-byte – Stefan Haustein Nov 22 '16 at 00:11

0 Answers0