Description
Loads a byte value (e.g., a value loaded from a byte array or returned by a method with return type byte) and performs a bitwise OR with that value. Byte values are sign extended to 32 bits before any any bitwise operations are performed on the value. Thus, if b[0] contains the value 0xff, and x is initially 0, then the code ((x « 8) | b[0]) will sign extend 0xff to get 0xffffffff, and thus give the value 0xffffffff as the result.
byte與int做or時,由於byte被轉成int,若此byte大於等於0x80,它將變成0xffffff80。
Solution
將byte與0xff做and,以去除其負數部分。
Example
Before:
public static short byteArrayToShort(byte[] b) { final short ret; ret = (short) (b[0] << 8 | b[1] ); return ret; }
After:
public static short byteArrayToShort(byte[] b) { final short ret; ret = (short) (b[0] << 8 | b[1] & 0xff); return ret; }
如果將0x00與0xff傳入修改之前的程式碼,預期值為255(0x00ff),但結果會為-1(0xffff)。
留言
張貼留言