55

如何short在 Java 中将(2 个字节)转换为字节数组,例如

short x = 233;
byte[] ret = new byte[2];

...

它应该是这样的。但不确定。

((0xFF << 8) & x) >> 0;

编辑:

您也可以使用:

java.nio.ByteOrder.nativeOrder();

发现以获取原始位顺序是大还是小。此外,以下代码取自java.io.Bits其中:

  • 字节(数组/偏移量)到布尔值
  • 字节数组到 char
  • 字节数组短
  • 字节数组到 int
  • 要浮动的字节数组
  • 字节数组长
  • 字节数组加倍

反之亦然。

4

9 回答 9

82
ret[0] = (byte)(x & 0xff);
ret[1] = (byte)((x >> 8) & 0xff);
于 2010-02-02T23:56:26.497 回答
47

一个更清洁但效率低得多的解决方案是:

ByteBuffer buffer = ByteBuffer.allocate(2);
buffer.putShort(value);
return buffer.array();

当您将来必须进行更复杂的字节转换时,请记住这一点。ByteBuffers 非常强大。

于 2011-06-24T19:39:55.493 回答
19

更有效的替代方案:

    // Little Endian
    ret[0] = (byte) x;
    ret[1] = (byte) (x >> 8);

    // Big Endian
    ret[0] = (byte) (x >> 8);
    ret[1] = (byte) x;
于 2013-05-24T11:41:23.680 回答
7

想通了,它:

public static byte[] toBytes(short s) {
    return new byte[]{(byte)(s & 0x00FF),(byte)((s & 0xFF00)>>8)};
}
于 2010-02-02T23:57:39.917 回答
7

Kotlin 中的短字节转换方法对我有用:

 fun toBytes(s: Short): ByteArray {
    return byteArrayOf((s.toInt() and 0x00FF).toByte(), ((s.toInt() and 0xFF00) shr (8)).toByte())
}
于 2017-12-20T11:45:32.723 回答
4

这里提到了几种方法。但是哪一个是最好的?下面是一些证明,以下 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);

结论:少即是多?

byte b1 = (byte) (s >> 8);
byte b2 = (byte) s;

(正如其他答案所提到的,请注意LE/BE)。

于 2015-08-17T11:13:29.410 回答
3

这取决于您要如何表示它:

  • 大端还是小端?这将确定您将字节放入的顺序。

  • 您想使用 2 的补码还是其他方式来表示负数?您应该使用与 java 中的 short 具有相同范围的方案来进行 1 对 1 映射。

对于大端,转换应该是这样的:ret[0] = x/256; ret[1] = x%256;

于 2010-02-02T23:59:18.793 回答
1
public short bytesToShort(byte[] bytes) {
     return ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getShort();
}

public byte[] shortToBytes(short value) {
    byte[] returnByteArray = new byte[2];
    returnByteArray[0] = (byte) (value & 0xff);
    returnByteArray[1] = (byte) ((value >>> 8) & 0xff);
    return returnByteArray;
}
于 2013-08-08T06:27:04.210 回答
0

短字节

short x=17000;    
byte res[]=new byte[2];    
res[i]= (byte)(((short)(x>>7)) & ((short)0x7f) | 0x80 );    
res[i+1]= (byte)((x & ((short)0x7f)));

字节短

short x=(short)(128*((byte)(res[i] &(byte)0x7f))+res[i+1]);
于 2015-11-17T04:38:36.663 回答