字节数组与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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值