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

我正在尝试将短路转换为2个字节…然后从这2个字节尝试获得相同的短路值。 为此,我写了这段代码:

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中以任何本地方式执行此操作? 提前致谢!

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

 Eg 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 

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

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