How to convert byte [] to POSITIVE BigInteger in Java?

I work with another team that works in C. The protocol we are communicating with sends an IP address in the format byte [], as well as 2 mask values, which are bytes [8]. I would like to use an IP address like BigInteger so that I can do comparisons to find out if the IP address is between two other IP addresses. To ensure that the signature does not hurt me, I need a way to convert IP from byte [] (either 4 bytes for IPv4 or 16 bytes for IPv6) to a positive value in BigInteger. Can someone point me to a link or suggest a method for its implementation?

+6
source share
3 answers

Java has a BigInteger constructor that accepts a signed integer and an array of bytes. So you can do:

BigInteger ip = new BigInteger(1, ipBytes); 

See the docs here: BigInteger (int, byte [])

+13
source

As others have noted, the BigInteger constructor should be fine. It is worth noting that the JVM is a big endiator, so just make sure that the byte array you are passing in is as well. You do not need to do anything if you get bytes from the socket, since the network byte order is also large, but this can be a problem if you are running on a small end computer such as x86 and receiving data through some other means.

+2
source

Source: https://habr.com/ru/post/893296/


All Articles