我正在使用以下方法将 byte 转换为 short,
short shortvalue;
nTempByteArr[0] = RawDataQueue.poll();
nTempByteArr[1] = RawDataQueue.poll();
ShortValue = (short) (((nTempByteArr[1] & 0xff) << 8) | (nTempByteArr[0] & 0xff));
如何将短值转换为完全相同的两个字节 nTempByteArr[0] 和 nTempbyteArr[1]
我试过:
nByteArr[0] = (byte)((ShortValue & 0xff00) >> 8);
nByteArr[1] = (byte)(ShortValue & 0xff);
nByteArr[0] = (byte)( ShortValue & 0xff);
nByteArr[1] = (byte)((ShortValue & 0xff00) >> 8);
请帮助我...!!!!!!!!!!!!
最佳答案
我们可以使用另一种不带移位的方法将 bytes
转换为 short
而无需移位,方法是使用 java.nio.ByteBuffer
ByteBuffer bb = ByteBuffer.allocate(2);
bb.order(ByteOrder.LITTLE_ENDIAN);
bb.put(nTempByteArr[1]);
bb.put(nTempByteArr[0]);
short shortVal = bb.getShort(0);
然后我们可以使用ByteBuffer
的get
函数来帮助我们返回bytes
bb.putShort(ShortValue);
nTempByteArr[0] = bb.get(0);
nTempByteArr[1] = bb.get(1);
关于c# - 我想用以下方法将 short 转换为 byte,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20559764/