Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a byte[] to a POSITIVE BigInteger in Java?

Tags:

java

math

binary

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?

like image 504
Deven Phillips Avatar asked Jul 21 '11 17:07

Deven Phillips


People also ask

How many bytes is BigInteger Java?

That's a total of 20 bytes + the integer array.

How do I convert String to BigInteger?

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.


1 Answers

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[])

like image 139
Richard Campbell Avatar answered Oct 19 '22 22:10

Richard Campbell