• (byte & 0xff)操作


    先看一段代码:

        @Test
        public void test(){
            byte a = -5;
            byte b = 12;
            System.out.println(a);
            System.out.println(Integer.toHexString(a));
            System.out.println(Integer.toHexString(a & 0xff));
            System.out.println(b);
            System.out.println(Integer.toHexString(b));
            System.out.println(Integer.toHexString(b & 0xff));
        }

    执行结果:

    -5
    fffffffb
    fb
    12
    c
    c

    解释:

    1.负数在计算机中以补码形式保存,所以-5的二进制表示为11111011(负数补码的计算方式:绝对值的反码+1)

    2.byte转换为int时,左边的24位补符号位,对于-5,转换后的二进制表示为11111111111111111111111111111011,这与之前的11111011,十进制都表示为-5,所以输出为-5

    3.0xff为一个int整数,255,二进制表示为00000000000000000000000011111111,-5 & 0xff,即将-5的高24位置0

    4.Integer.toHexString函数,循环右移,每次取4位,转换为16进制字符串,所以11111111111111111111111111111011转成16进制字符串,前面出现多次的'1111'都转成了'f'

    Integer.toHexString源码如下:

    /**
         * Convert the integer to an unsigned number.
         */
    //shift=4
        private static String toUnsignedString(int i, int shift) {
            char[] buf = new char[32];
            int charPos = 32;
            int radix = 1 << shift;
            int mask = radix - 1;
            do {
                buf[--charPos] = digits[i & mask];
                i >>>= shift;
            } while (i != 0);
    
            return new String(buf, charPos, (32 - charPos));
        }
        
        /**
         * All possible chars for representing a number as a String
         */
        final static char[] digits = {
            '0' , '1' , '2' , '3' , '4' , '5' ,
            '6' , '7' , '8' , '9' , 'a' , 'b' ,
            'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
            'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
            'o' , 'p' , 'q' , 'r' , 's' , 't' ,
            'u' , 'v' , 'w' , 'x' , 'y' , 'z'
        };
  • 相关阅读:
    使用xdebug调试PHP程序
    删除有序数组中的重复元素
    libmysql.dll与php.ini是否真的要拷贝到c:\windows目录下呢
    C++中的纯虚方法
    排序算法:堆排序算法实现及分析
    虚拟蜜罐honeyd安装使用
    软件目录结构规范(以python为例)
    python源码为何都是pass
    对类的实例直接赋值
    Path Analyzer Pro出现raw socket问题
  • 原文地址:https://www.cnblogs.com/darange/p/10715604.html
Copyright © 2020-2023  润新知