java中byte,byte[]和int之间的转换

1>byte类型转换为,直接隐式转换,适用于要求保持数值不变,例如要求进行数值计算 如 byte b=0x01; int i=b;

2>另一种是要求保持最低字节中各个位不变,3个高字节全部用0填充,例如进行编解码操作,则需要采用位操作,int i=b & 0xff;

3>byte[]数组和int之间的转换

// 将byte[]转换为int类型
    public static int byte2int(byte[] res) {
        // 一个byte数据左移24位变成0x??000000,再右移8位变成0x00??0000

        int targets = (res[0] & 0xff) | ((res[1] << 8) & 0xff00) // | 表示安位或
                | ((res[2] << 24) >>> 8) | (res[3] << 24);
        return targets;
    }

    // 将int类型装换为byte[]数组
    public static byte[] int2byte(int res) {
        byte[] targets = new byte[4];

        targets[0] = (byte) (res & 0xff);// 最低位
        targets[1] = (byte) ((res >> 8) & 0xff);// 次低位
        targets[2] = (byte) ((res >> 16) & 0xff);// 次高位
        targets[3] = (byte) (res >>> 24);// 最高位,无符号右移。
        return targets;
    }