& 0xFF 作用 取低8位

& 0xFF 取低8位

@Test
void byteTest() {

    byte hex1 = (byte) 127;
    byte hex2 = (byte) 383;
    byte hex3 = (byte) 0x7F;

    RandomAccessFile writeFile = null;
    try {
        //写入头文件
        writeFile = new RandomAccessFile("D:\\temp\\hex.txt", "rw");
        byte[] bytes = new byte[3];
        bytes[0] = hex1;
        bytes[1] = hex2;
        bytes[2] = hex3;
        writeFile.write(bytes, 0, bytes.length);
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
    } finally {
        try {
            if (writeFile != null) {
                writeFile.close();
            }
        } catch (Exception ex) {

        }
    }
    logger.info("成功");
}

 

@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、int 转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;
}


/**
 * int 转 byte 同理
 */
public static byte[] intToBytes(int intValue, ByteOrder byteOrder) {

    if (ByteOrder.LITTLE_ENDIAN == byteOrder) {
        return new byte[]{
                (byte) (intValue & 0xFF),
                (byte) ((intValue >> 8) & 0xFF),
                (byte) ((intValue >> 16) & 0xFF),
                (byte) ((intValue >> 24) & 0xFF)
        };

    } else {
        return new byte[]{
                (byte) ((intValue >> 24) & 0xFF),
                (byte) ((intValue >> 16) & 0xFF),
                (byte) ((intValue >> 8) & 0xFF),
                (byte) (intValue & 0xFF)
        };
    } 
}

 

posted @ 2022-05-07 11:17  VipSoft  阅读(277)  评论(0编辑  收藏  举报