重组时,需要屏蔽字节1以停止对其进行符号扩展。
例如
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
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)