在Java中从short转换为byte,反之亦然

时间:2010-06-25 01:10:41

标签: java byte typeconverter short

我正在尝试将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.经过一些测试,它看起来像这个代码只适用于某些值。就像...如果oldshort = 50,那么它将正常工作..但如果它是-200,或更大的值超过127(我认为)它不起作用。我想有签名的字节,二的补码值等问题......但我无法弄清楚如何解决它。

任何想法?在java中以任何本地方式执行此操作?提前谢谢!

2 个答案:

答案 0 :(得分:5)

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

E.g。

    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中字节和短路的所有操作实际上都是以整数形式完成的。所以当你写作 +byte1,真正发生的是字节首先被转换为整数(符号扩展)。它仍然具有相同的值,但现在有更多的位。然后,我们可以屏蔽底部的8位,从短路中获取原始的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

答案 1 :(得分:0)

您还可以使用com.google.common.primitives.Shorts,其中包含以下方法:

  • public static byte[] toByteArray(short value)
  • public static short fromByteArray(byte[] bytes)