I have a byte array has follows:

0 6 -56 28

How can I get its integer value by doing a manual calculation?

If you have an array of `Byte()` class, then the class itself has an `intValue()` method that returns the value of this Byte as an int.

Actually I want 2 convert it into integer manually.

then you will have to use your own binary to decimal function and pass it the byte value.

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 an unsigned int, use the above expression but store in a long. To reverse the endianness, obviously put b0-b3 the other way round.

I said the same thing, the only thing is I left the logic part for him to figure out, and I feel thats what was supposed to be done.

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!

Array of `Byte` means

``Byte [] byteArray = new Byte [5];``

I don't know how else to explain, but this certainly was picked up by the original poster since he asked me the next question on that, which told us he wanted to convert the bytes to integer manually. My response to this post "then you need to write your own binary to decimal function" explains the next step without going into unecesary details, which as I mentioned should be left to the OP to be figured out.

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.

On pondering over it now, I feel, even I might have misinterpreted, cause this 4 bytes thing didn't cross my mind, I was of the notion that he wanted the integer value of each of them. Well, nevermind, the OP has both the solutions, he can choose the appropriate one. Cheers !!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.