3

我正在尝试将 short 转换为 2 个字节......然后从这 2 个字节尝试获得相同的 short 值。为此,我编写了以下代码:


        short oldshort = 700;

        byte 333= (byte) (oldshort);
        byte byte2= (byte) ((oldshort >> 8) & 0xff);

        short newshort = (short) ((byte2 << 8) + byte1);

            System.out.println(oldshort);
        System.out.println(newshort);

对于 700 (oldshort) 的值,newhosrt 是 444。经过一些测试,它看起来像 \t 此代码仅适用于某些值。就像...如果oldshort = 50,那么它会正常工作..但如果它是-200,或者大于127的值(我认为)它不起作用。我想有符号字节,二进制补码值等存在问题......但我不知道如何解决它。

任何想法??在java中有任何本地方法可以做到这一点吗?提前致谢!

4

2 回答 2

5

重新组合时,您需要屏蔽 byte1 以阻止它被符号扩展。

例如

    short oldshort = 700;

    byte byte1= (byte) (oldshort);
    byte byte2= (byte) ((oldshort >> 8) & 0xff);

    short newshort = (short) ((byte2 << 8) + (byte1&0xFF);

        System.out.println(oldshort);
    System.out.println(newshort);

编辑:java中对字节和shorts的所有操作实际上都是作为整数完成的。因此,当您编写 时 +byte1,真正发生的是字节首先转换为整数(符号扩展)。它仍然具有相同的值,但现在有更多位。然后,我们可以屏蔽掉底部的 8 位,以从 short 中获取原始的 8 位 - 没有符号。

E.g. short =511 = 0x01FE
     // lots of 0x000's because the operations are done on 32-bit int's
     byte1 = (0x000001FE & 0x000000FF) = (0x01FE & 0xFF) = 0xFE = (byte)-2
     byte2 = 0x1

     newShort = (byte2 << 8) + (byte1 & 0xFF)
              = (0x1 << 8) + (0xFE & 0xFF)
            // since the ops are performed as int's
              = (0x00000001 << 8) + (0xFFFFFFFE & 0x000000FF)
            // 0xFFFFFFFE = -2 
              = (0x00000100) + (0x000000FE)
              = 0x000001FE
              = 511
于 2010-06-25T01:20:43.953 回答
1

您也可以使用com.google.common.primitives.Shorts,它有方法:

  • public static byte[] toByteArray(short value)
  • public static short fromByteArray(byte[] bytes)
于 2017-11-20T20:33:14.757 回答