Converting Byte Arrays to an Integer

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.
anicklesAsked:
Who is Participating?
 
doraemon-nolifeConnect With a Mentor Commented:
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
 
CEHJConnect With a Mentor Commented:
>>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
 
CEHJCommented:
>>
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
 
CEHJCommented:
:-)

Sorry - i assumed you knew there is a long in Java
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.