开发者

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

开发者 https://www.devze.com 2023-03-22 05:17 出处:网络
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

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 ens开发者_JAVA技巧ure 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?


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


Just use the constructor which accepts a byte array and a parameter to say whether it's positive or negative.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号