[英]I want to convert short to byte with following approach
我正在使用以下方法将字节转换为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);
请帮我...!!!!!!!!!!!!!
我们可以通过使用java.nio.ByteBuffer
使用另一种不带移位的方法将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);
short s = ...
byte b1 = (byte)((s >> 8) & 0xff);
byte b2 = (byte)(s & 0xff);
尝试这个
(数字>>> 8)&0xFF; (数字>>> 0)&0xFF;
(short)((portArray [0] << 8)|(portArray [1])&0xff);
我的解决方案是正确的。 还有其他问题,因为只有它无法获得正确的字节
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.