1. 程式人生 > 其它 >& 0xFF 作用 取低8位

& 0xFF 作用 取低8位

& 0xFF 取低8位

@Test
void lowerOrderTest() {
    // 65304 = 1111 1111 0001 1000

    int h1 = ((65304));  //直接返回原資料 => 65304
    int h2 = ((65304 >> 4)); //右移4位,高位補0 => 0000 1111 1111 0001 => 1111 1111 0001 => 4081

    /**
     *  取低8位(FF)
     *  0xFFF = 11111111
     *  & 相同數為1 不同數為0
     *  1111 1111 0001 1000
     *            1111 1111
     *  0000 0000 0001 1000
     *  11000 => 24
     
*/ int h3 = ((65304) & 0xFF); /** * >> 4 先右移4位, 高位補0 * 1111 1111 0001 1000 * 0000 1111 1111 0001 * & 0xFF 取低8位 * 0000 1111 1111 0001 * 1111 1111 * 0000 0000 1111 0001 * 11110001 => 241 */ int h4 = ((65304 >> 4) & 0xFF); logger.info("\n{}\n{}\n{}\n{}",h1,h2,h3,h4); }
 short轉byte陣列
/**
 * 32536 => 0111 1111 0001 1000 最左邊為符號位
 * 預設從低位到高位的順序取值
 * b[0] = 111 1111 0001 1000 & 0xFF = 0001 1000 = 24
 * b[1] = 111 1111 0001 1000 >> 8 & 0xFF = 0111 1111 = 127
* 由高到低同理
*/ public static byte[] shortToBytes(short shortValue, ByteOrder byteOrder) { byte[] b = new byte[Short.BYTES];
if (ByteOrder.LITTLE_ENDIAN == byteOrder) { b[0] = (byte) (shortValue & 0xFF); b[1] = (byte) ((shortValue >> Byte.SIZE) & 0xff); } else { b[1] = (byte) (shortValue & 0xFF); b[0] = (byte) ((shortValue >> Byte.SIZE) & 0xff); } return b; }