Search code examples
javabinaryfilesunsigned

Convert 2 byte (unsigned short) to Java short from binary file


i have binary file with unsigned shorts. I need to take unsigned value from this bytes to primitive short in JAVA. Byte order is Little Endian. I trying in this way:

    byte[] bytes = new byte[frameLength];
    for(int i = 0; i < fh.nFrames; i++) {
        raf.readFully(bytes);
        for(int j = 2; j < frameLength/2; j++) {
            short s;
            s = (short) (bytes[2*j + 1] << 8 | bytes[2 * j]);       
            System.out.println(s);
            System.out.println(Integer.toBinaryString(s));
        }
    }

Example: case 1(ok): unsigned short : 8237 in hex(little endian): 2D 20 in binary(big endian): 0010 0000 0010 1101 and System.out.println(Integer.toBinaryString(s)) give us 10000000101101. It's correct.

case 2(not ok) unsigned short: 384 in hex(little endian): 80 01 in binary(big endian): 0000 0001 1000 0000 and System.out.println(Integer.toBinaryString(s)) give us 11111111111111111111111110000000. System.out.println(s) give us -128. It's not correct. How i can get 384 value from this?

Someone has idea why it doesn't working?


Solution

  • Java converts everything to int before doing integer computations, and as bytes are signed, you get a sign extension. You must force bytes to stay in [0; 255] range by bitwise and-ing them with 0xFF:

    s = (short) ((bytes[2*j + 1] & 0xFF) << 8 | (bytes[2 * j] & 0xFF));