public static void main(String[] args) throws Exception {
short sh = 100;
printBytesString(shortToBytes1(sh));
System.out.println();
printBytesString(shortToBytes2(sh));
}
public static byte[] shortToBytes1(short sNum) {
byte[] bytesRet = new byte[2];
bytesRet[0] = (byte)((sNum >> 8) & 0xFF);
bytesRet[1] = (byte)(sNum & 0xFF);
return bytesRet;
}
public static byte[] shortToBytes2(short sNum) {
byte[] bytesRet = new byte[2];
bytesRet[0] = (byte)(sNum >> 8);
bytesRet[1] = (byte)(sNum);
return bytesRet;
}
输出: 0000000001100100 0000000001100100
结果是一样的。那么,shortToBytes1()和shortToBytes2()之间的区别是什么?
答案 0 :(得分:0)
shortToBytes1
首先将字节转换为unsigned int值,而第二个则不转换。我建议使用第一个。