java的int和byte数组的相互转换

[size=medium]byte数组转为int
有两种原理,
一种是先左移动24位,在无符号右移 对应的是byte2int3
另外一种是 先移动 在把干扰的和0做与操作,消除干扰(byte负数的时候 右移时左边都是1,这个时候是有干扰的) 对应的是byte2int2
还有就是这两种的结合了 对应byte2int

注意这个转成byte和实际int的byte的顺序是相反的,不要理解错了。
这样写的原因是写起来更好看,功能反正是ok的
[/size]


public static int byte2int(byte[] res) {
int targets = (res[0] & 0xff) | ((res[1] << 8) & 0xff00)
| ((res[2] << 24) >>> 8) | (res[3] << 24);
return targets;
}


public static int byte2int2(byte[] res) {
int targets = (res[0] & 0xff) | ((res[1] << 8) & 0xff00)
| ((res[2] << 16) & 0xff0000) | (res[3] << 24);
return targets;
}

public static int byte2int3(byte[] res) {
int targets = ((res[0] << 24) >>> 24) | ((res[1] << 24) >>> 16)
| ((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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值