字节数组与int相互转换

package Util;

/**
 *数据工具类
 */

public class DataUtil {
    //工具类的方法是静态的
    public static byte [] int2bytes(int i){
        byte [] bytes = new byte[4];
        bytes[0] = (byte)(i >>0) ;
        //此处有符号移动还是无符号移动无所谓,因为&0xff后,高位全是0了,只留下低8位
        bytes[1] = (byte)(i >>>8);
        bytes[2] = (byte)(i >>>16);
        bytes[3] = (byte)(i >>>24);
        return bytes;
    }

    public static int bytes2int(byte [] arr){
        //最低位为什么还进行&运算
        //因为arr[0] & 0xff后结果自动升格为int型,那么如果是负数,高24位会全部变成1
         int a = arr[0] & 0xff;
         int b = (arr[1] &0xff)<< 8;
         int c = (arr[2] & 0xff) << 16;
         int d = (arr[3] & 0xff) << 24;
         return  a | b | c | d;
    }
    public static void main(String [] argc){
        byte [] bytes = int2bytes(255);
        int a = bytes2int(bytes);
        System.out.println(a);
    }
}
发布了85 篇原创文章 · 获赞 40 · 访问量 23万+

猜你喜欢

转载自blog.csdn.net/ljb825802164/article/details/89855002