• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

how to convert byte[] to int in Java?

Does java support unions?
In C:
union foo {
byte java[2];
int sucks;
}

void myfunc()
{
union foo bar;
int stuf;
bar.java[0] = 0;
bar.java[1] = -1;
stuff = bar.sucks;
}

edit: by the way, on most systems, int = 4 bytes, short = 2 bytes.
 
int temp = new Byte(tmpByte[0]).intValue();
int temp2 = new Byte(tmpByte[1]).intValue();

Find more byte references:
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Byte.html

Bah, just realized, you want to combine two bytes into 1 int, hold on a min....

Ok, two bytes to 1 32-bit integer:

int temp = ((int)tmpByte[0] << 8) + (tmpByte[1] & 0xff);

Three bytes:

int temp = ((int)tmpByte[0] << 16 ) + ((tmpByte[1] & 0xff) << 8 ) + (tmpByte[2] & 0xff);

Four bytes:

int temp = ((tmpByte[0] & 0xff) << 24 ) + ((tmpByte[1] & 0xff) << 16 ) + ((tmpByte[2] & 0xff) << 8 ) + ((tmpByte[3] & 0xff) );
 
Originally posted by: Jumpem
What does the "<< 8" portion do in your example?

int temp = ((int)tmpByte[0] << 8) + (tmpByte[1] & 0xff);

shift by 8, so if your original bit pattern for byte0 was 0000000010101010, the new pattern would be 1010101000000000. Then the addition adds the lower byte, producing the complete number.
 
Originally posted by: Jumpem
Ok, I understand that. What does the "& 0xff" portion do?
Ensure that any garbage in the upper byte is cleaned off before use.

 
Back
Top