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?
That's a total of 20 bytes + the integer array.
One way is to use the BigInteger(String value, int radix) constructor: String inputString = "290f98"; BigInteger result = new BigInteger(inputString, 16); assertEquals("2690968", result. toString()); In this case, we're specifying the radix, or base, as 16 for converting hexadecimal to decimal.
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[])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With