如何short在Java中将(2个字节)转换为字节数组,例如
short x = 233;
byte[] ret = new byte[2];
...
Run Code Online (Sandbox Code Playgroud)
它应该是这样的.但不确定.
((0xFF << 8) & x) >> 0;
Run Code Online (Sandbox Code Playgroud)
编辑:
你也可以使用:
java.nio.ByteOrder.nativeOrder();
Run Code Online (Sandbox Code Playgroud)
发现以获取本机位顺序是大还是小.另外,以下代码取自java.io.Bits:
反之亦然.
Ale*_*ler 73
ret[0] = (byte)(x & 0xff);
ret[1] = (byte)((x >> 8) & 0xff);
Run Code Online (Sandbox Code Playgroud)
Gil*_*ili 35
一个更清洁,虽然效率低得多的解决方案是:
ByteBuffer buffer = ByteBuffer.allocate(2);
buffer.putShort(value);
return buffer.array();
Run Code Online (Sandbox Code Playgroud)
在将来必须进行更复杂的字节转换时,请记住这一点.ByteBuffers非常强大.
Dav*_*vid 14
一种更有效的替代方案:
// Little Endian
ret[0] = (byte) x;
ret[1] = (byte) (x >> 8);
// Big Endian
ret[0] = (byte) (x >> 8);
ret[1] = (byte) x;
Run Code Online (Sandbox Code Playgroud)
弄清楚了,它:
public static byte[] toBytes(short s) {
return new byte[]{(byte)(s & 0x00FF),(byte)((s & 0xFF00)>>8)};
}
Run Code Online (Sandbox Code Playgroud)
短字节转换方法在 Kotlin 中对我有用:
fun toBytes(s: Short): ByteArray {
return byteArrayOf((s.toInt() and 0x00FF).toByte(), ((s.toInt() and 0xFF00) shr (8)).toByte())
}
Run Code Online (Sandbox Code Playgroud)
这里已经提到了几种方法。但哪一个是最好的呢?以下是一些证明,证明以下 3 种方法对于 a 的所有值都会产生相同的输出short
// loops through all the values of a Short
short i = Short.MIN_VALUE;
do
{
// method 1: A SIMPLE SHIFT
byte a1 = (byte) (i >> 8);
byte a2 = (byte) i;
// method 2: AN UNSIGNED SHIFT
byte b1 = (byte) (i >>> 8);
byte b2 = (byte) i;
// method 3: SHIFT AND MASK
byte c1 = (byte) (i >> 8 & 0xFF);
byte c2 = (byte) (i & 0xFF);
if (a1 != b1 || a1 != c1 ||
a2 != b2 || a2 != c2)
{
// this point is never reached !!
}
} while (i++ != Short.MAX_VALUE);
Run Code Online (Sandbox Code Playgroud)
结论:少即是多?
byte b1 = (byte) (s >> 8);
byte b2 = (byte) s;
Run Code Online (Sandbox Code Playgroud)
(正如其他答案所提到的,请注意LE/BE)。
| 归档时间: |
|
| 查看次数: |
82990 次 |
| 最近记录: |