java short 类型转byte[],带正负,2种方法
方法一、这种方法跟正负没与关系
public static int swap_16(int date){
int a,b;
a = (date>>8)&0x00ff;
b = (date<<8)&0xff00;
return (a+b);
}
public static byte[] short2ByteNew(short x){
byte high = (byte) (0x00FF & (x>>8));//定义第一个byte
byte low = (byte) (0x00FF & x);//定义第二个byte
// System.out.println(high);//打印第一个byte值
// System.out.println(low);//打印第二个byte值
byte[] bytes = new byte[2];
bytes[0] = high;
bytes[1] = low;
return bytes;
}
public static short byte2shortNew(byte[] bytes){
byte high = bytes[0];
byte low = bytes[1];
short z = (short)(((high & 0x00FF) << 8) | (0x00FF & low));
return z;
}
方法二、有正负的short值区间在-32768~32768之间,如果大于32768则需要这个值-65536
int tpmin = buffer.getShort()&0xffff;
if(tpmin>32768){
// int tmp1 = AndroidUtils.swap_16(tpmin);
edtp_alarmParam_MinRange.setText((tpmin-65536)+"");
}else{
edtp_alarmParam_MinRange.setText(String.valueOf(tpmin));
}
说下大小端问题
如果一个值0x12 34 56 78 如果按照 byte[0]=0x12 byte[1]=0x12 byte[2]=0x56 byte[3]=0x78
Bytebuffer bytebuffer= ByteBuffer.allocate(57);
bytebuffer.order(ByteOrder.LITTLE_ENDIAN);
bytebuffer.put(byte[0])
bytebuffer.put(byte[1])
bytebuffer.put(byte[2])
bytebuffer.put(byte[3])
这时候是不需要大小端转换,原因是本身已经是这种排列方式
0xfffc = 65532
需要先把65532大小端转换 fcff
由于bytebuffer.order(ByteOrder.LITTLE_ENDIAN);
大港bytebuffer.putshort(fcff)后,你在通过bytebuffer读就死fffc了