ara*_*kn0 3 java byte short typeconverter
我正在尝试将短路转换为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);
Run Code Online (Sandbox Code Playgroud)
对于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);
Run Code Online (Sandbox Code Playgroud)
编辑: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
Run Code Online (Sandbox Code Playgroud)