在网上找到的资料,忘记了出处。
/**
* 注释:short到字节数组的转换!
*
* @param s
* @return
*/
public static byte[] shortToByte(short number) {
int temp = number;
byte[] b = new byte[2];
for (int i = 0; i < b.length; i++) {
b[i] = new Integer(temp & 0xff).byteValue();// 将最低位保存在最低位 ,即b[0] 放低位,b[1]放高位。
temp = temp >> 8; // 向右移8位
}
return b;
}
/**
* 注释:字节数组到short的转换!
*
* @param b
* @return
*/
public static short byteToShort(byte[] b) {
short s = 0;
short s0 = (short) (b[0] & 0xff);//低位,与0xff位与可以消除自动添加负数位,补码表示
short s1 = (short) (b[1] & 0xff); //高位
s1 <<= 8;
s = (short) (s0 | s1);
return s;
}