基於小端規則的幾個java方法

softkf發表於2016-01-26
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。

 

 

 

 

 

 

 

 

相關文章