Does Java read integers in little endian or big endian?

后端 未结 8 1727
孤城傲影
孤城傲影 2020-11-27 13:30

I ask because I am sending a byte stream from a C process to Java. On the C side the 32 bit integer has the LSB is the first byte and MSB is the 4th byte.

So my ques

8条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-27 13:42

    Java is 'Big-endian' as noted above. That means that the MSB of an int is on the left if you examine memory (on an Intel CPU at least). The sign bit is also in the MSB for all Java integer types.
    Reading a 4 byte unsigned integer from a binary file stored by a 'Little-endian' system takes a bit of adaptation in Java. DataInputStream's readInt() expects Big-endian format.
    Here's an example that reads a four byte unsigned value (as displayed by HexEdit as 01 00 00 00) into an integer with a value of 1:

     // Declare an array of 4 shorts to hold the four unsigned bytes
     short[] tempShort = new short[4];
     for (int b = 0; b < 4; b++) {
        tempShort[b] = (short)dIStream.readUnsignedByte();           
     }
     int curVal = convToInt(tempShort);
    
     // Pass an array of four shorts which convert from LSB first 
     public int convToInt(short[] sb)
     {
       int answer = sb[0];
       answer += sb[1] << 8;
       answer += sb[2] << 16;
       answer += sb[3] << 24;
       return answer;        
     }
    

提交回复
热议问题