Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Convert 4 bytes to int

i was wondering if the solution for this documented here is still the solution or is there any other way getting an int from 4 bytes?

thank you.

EDIT: im getting the byte[] from sockets .read

EDIT: int recvMsgSize = in.read(Data, 0, BufferSize); if recvMsgSize is -1 i know the connection has been dropped.

how do i detect this when im using DataInputStream instead of InputStream?

thanks.

EDIT: apologies for being a yoyo regarding accepting the right answer. but after mihi's updated final response, it would appear that the method is solid and cuts down extended coding and in my opinion best practice.

like image 990
iTEgg Avatar asked May 15 '10 13:05

iTEgg


1 Answers

You have to be very careful with any widening conversion and numeric promotion, but the code below converts 4 byte into int:

    byte b1 = -1;
    byte b2 = -2;
    byte b3 = -3;
    byte b4 = -4;
    int i = ((0xFF & b1) << 24) | ((0xFF & b2) << 16) |
            ((0xFF & b3) << 8) | (0xFF & b4);
    System.out.println(Integer.toHexString(i)); // prints "fffefdfc"

See also

  • Java code To convert byte to Hexadecimal
    • Pay attention to the need to mask with & 0xFF -- you'll probably end up doing a lot of this if you're working with byte since all arithmetic operations promote to int (or long)
like image 82
polygenelubricants Avatar answered Oct 12 '22 10:10

polygenelubricants