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

基于小端规则的几个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。