You have a couple of options:
- Use the ByteBuffer class (link is to a tutorial I wrote in case helpful), for example:
ByteBuffer bb = ByteBuffer.allocate(4);
bb.put((byte) ...);
bb.put((byte) ...);
bb.put((byte) ...);
bb.put((byte) ...);
int intVal = bb.getInt(0);
- More efficiently, just manually code it with shifts and ORs. You also generally have to be careful to AND each byte value with 0xff to remove the sign:
int intVal = ((b0 & 0xff) << 24) | ((b1 & 0xff) << 16) | (b2 & 0xff) << 8) | (b3 & 0xff);
For anunsigned int, use the above expression but store in a long. To reverse the endianness, obviously put b0-b3 the other way round.
neilcoffey
Junior Poster in Training
53 posts since Dec 2008
Reputation Points: 120
Solved Threads: 7
Sorry, I really didn't understand "array of Byte() class" was supposed to tell the poster to do the above. I'm going to wager that they didn't either!
neilcoffey
Junior Poster in Training
53 posts since Dec 2008
Reputation Points: 120
Solved Threads: 7
Ah, you mean convert each individual byte into an unsigned int. If that's really what the poster meant, then sorry -- I misinterpreted. But I think the poster means that they want to amalgamate the four bytes and get a single, four-byte integer value.
By the way, for converting a byte to an int, just ANDing with 0xff is common and efficient.
neilcoffey
Junior Poster in Training
53 posts since Dec 2008
Reputation Points: 120
Solved Threads: 7