Solved

# Converting Byte Arrays to an Integer

Posted on 2007-08-09
340 Views
In java I have a four byte array that contains the representation of an integer in network byte order. How can I convert this from a byte array to an integer? For example, the byte array might contain the following hex values "00 00 ff ff" which represents 65535. Another example is the hex value "00 00 00 80" represents 128. I thnk what is making this difficult is that converting from a byte to an integer results in a signed integer not an unsigned integer.
0
Question by:anickles

LVL 86

Assisted Solution

>>I thnk what is making this difficult is that converting from a byte to an integer results in a signed integer not an unsigned integer.

Well Java doesn't have unsigned integers

int i = new BigInteger(byteArray).intValue();
0

LVL 4

Accepted Solution

You can achieve the unsigned integer length using long

int (32 bit)
long (64 bit)  unsigned integer(should be 64 bit if it exist in java, but not now !)

borrow and modify a bit of CEHJ code:

long val = new BigInteger(byteArray).longValue();

:) Hope this help.
0

LVL 86

Expert Comment

>>
borrow and modify a bit of CEHJ code:

long val = new BigInteger(byteArray).longValue();
>>

No - that won't work as it will still be interpreted as a signed value.

long val = new BigInteger(1, byteArray).longValue();
0

LVL 86

Expert Comment

:-)

Sorry - i assumed you knew there is a long in Java
0

## Featured Post

Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different dâ€¦
You cannot be 100% sure that you can protect your organization against crypto ransomware but you can lower down the risk and impact of the infection.
This video teaches viewers about errors in exception handling.
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.