基于小端规则的几个java方法

public static byte[] InttoByteArray(int n) {
	byte[] b = new byte[4];
	b[0] = (byte) (n & 0xff);
	b[1] = (byte) (n >> 8 & 0xff);
	b[2] = (byte) (n >> 16 & 0xff);
	b[3] = (byte) (n >> 24 & 0xff);
	return b;
}
 
public static byte[] ShorttoByteArray(short n) {
	byte[] b = new byte[2];
	b[1] = (byte) (n & 0xff);
	b[0] = (byte) (n >> 8 & 0xff);
	return b;
}
 
public static int ByteArraytoInt(byte[] b) {
	int iOutcome = 0;
	byte bLoop;
	for (int i = 0; i < 4; i++) {
		bLoop = b[i];
		iOutcome += (bLoop & 0xff) << (8 * i);
	}
	return iOutcome;
}
 
public static short ByteArraytoShort(byte[] b) {
	short iOutcome = 0;
	byte bLoop;
	for (int i = 0; i < 2; i++) {
		bLoop = b[i];
		iOutcome += (bLoop & 0xff) << (8 * i);
	}
	return iOutcome;
}
 

附:通常字节序分为两类:Big-Endian和Little-Endian。具体如下
[1] Little-Endian:低位字节排放在内存的低地址端,高位字节排放在内存的高地址端。
[2] Big-Endian   :高位字节排放在内存的低地址端,低位字节排放在内存的高地址端。
[3] 网络字节序   :TCP/IP各层协议将字节序定义为Big-Endian。

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值