在 Java 中从短转换为字节,反之亦然
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3114935/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
convert from short to byte and viceversa in Java
提问by arakn0
I'm trying to convert a short into 2 bytes...and then from those 2 bytes try to get the same short value. For that, I've written this code:
我正在尝试将 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);
For the value of 700 (oldshort), newhosrt is 444. After some testing, it looksl ike \tThis code only works for some values. Like...if oldshort=50, then it will work fine..but if it is -200, or bigger values than 127 (i think) it doesn't work. I guess that there is a problem with the signed bytes, two's complement value, etc...but I can't figure out how to solve it.
对于700(oldshort)的值,newhostrt是444。经过一些测试,看起来像\t这段代码只对某些值有效。就像...如果 oldshort=50,那么它会正常工作...但如果它是 -200,或者大于 127 的值(我认为)它不起作用。我猜有符号字节,二进制补码值等有问题......但我不知道如何解决它。
Any idea?? Any native way to do this in java?? Thanks in advance!
任何的想法??任何在 Java 中执行此操作的本机方法?提前致谢!
回答by mdma
When recombining, you need to mask the byte1 to stop it being sign extended.
重组时,需要屏蔽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);
EDIT:
All operations on bytes and shorts in java are actually done as integers. So when you write
+byte1, what is really happening is that the byte is first cast to an integer (sign-extended). It will still have the same value, but now has more bits. We can then mask off the bottom 8 bits to get the original 8-bits from the short - without the sign.
编辑: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
回答by Liam Williams
You could also use com.google.common.primitives.Shorts, which has methods:
你也可以使用com.google.common.primitives.Shorts,它有方法:
public static byte[] toByteArray(short value)public static short fromByteArray(byte[] bytes)
public static byte[] toByteArray(short value)public static short fromByteArray(byte[] bytes)

