I am working with another team who is working in C. The protocol which we communicate with sends an IP address in byte[] format, as well as 2 "mask" values which are byte[8]. I would like to use the IP address as a BigInteger so that I can do comparisons to see if an IP address is between 2 other IP addresses. To ensure that signedness doesn't screw me up, I need a way to convert the IP from a byte[] (either 4 byte for IPv4 or 16 byte for IPv6) into a positive value in a BigInteger. Could someone point me to a reference or suggest a method of accomplishing this?
Asked
Active
Viewed 4,922 times
3 Answers
14
Java has a BigInteger constructor that takes a sign integer and a byte array. So you could do:
BigInteger ip = new BigInteger(1, ipBytes);
See the docs here: BigInteger(int, byte[])

Richard Campbell
- 3,591
- 23
- 18
-
just wondering... what this object return when we call toByteArray()? exactly the ipBytes parametr in constructor? – Marcin Mierzejewski Nov 30 '15 at 13:21
-
1No. `BigInteger.toByteArray()` returns a byte array including the sign, which can be used in the `BigInteger(byte[])` constructor. http://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigInteger.html#toByteArray() – Richard Campbell Nov 30 '15 at 14:57
-
maybe it's for another SO question I guess, but any problem how to get orginal bytes in this case? – Marcin Mierzejewski Nov 30 '15 at 15:47
-
1The original byte array will be edited as needed by BigInteger in construction - as shown here, all leading 0s will be removed http://stackoverflow.com/questions/5878603/how-does-biginteger-store-its-data - so there is no way to guarantee a return of the original bytes from a BigInteger other than to save a copy elsewhere. – Richard Campbell Nov 30 '15 at 15:52
-
and this comment propably saves me a lot time debuging. Thanks Richard! – Marcin Mierzejewski Nov 30 '15 at 16:14
12
Just use the constructor which accepts a byte array and a parameter to say whether it's positive or negative.

Michael Mrozek
- 169,610
- 28
- 168
- 175

OpenSauce
- 8,533
- 1
- 24
- 29
2
As others have noted the BigInteger constructor should be fine. One thing worth noting is that the JVM is big endian so just make sure that the byte array you're passing in is too. You shouldn't have to do anything if you're getting the bytes from a socket since network byte order is also big endian, but it could be an issue if you are running atop a little endian machine like x86 hardware and getting the data through some other means.

Erik Pilz
- 3,836
- 2
- 17
- 7