将 Short 转换为 Byte 时会发生什么?
我是 PHP 的 Java 新手,所以花一些时间/精力来理解类型。然后我遇到了这个:
Byte bb = new Byte("127");
System.out.println(bb.byteValue());
Short ss = new Short("32727");
System.out.println(ss.shortValue());
System.out.println(ss.byteValue());
输出 127、32727 和 -41 ?
有人可以向我解释当 Short 32727 表示为一个字节时它是如何到达 -41 的吗?
I'm new to Java, from PHP, so spending some time/effort understanding types. Then I came across this:
Byte bb = new Byte("127");
System.out.println(bb.byteValue());
Short ss = new Short("32727");
System.out.println(ss.shortValue());
System.out.println(ss.byteValue());
Outputs 127, 32727 and -41 ?
Can someone explain to me how it arrived at -41 when the Short 32727 is represented as a byte?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
32727 的二进制表示为 0111111111010111。它的 byteValue() 只是最小的 8 位,因此
11010111
11010111
是负数,因为它以 1 开头。 en.wikipedia.org/wiki/Two%27s_complement" rel="nofollow">二进制补码(对每一位求补,然后加一)给出
101001
是 2^5 + 2^3 + 2^0 = 32+8+1 = 41所以我们有 -41。
The binary representation of 32727 is
0111111111010111
. The byteValue() of that is just the smallest 8 bits, so11010111
11010111
is negative since it begins with a 1.Taking the Two's complement (complement each bit and then add one) gives
101001
which is 2^5 + 2^3 + 2^0 = 32+8+1 = 41So we have -41.
Java 只知道有符号类型。当您将 32727 截断为 8 位(即模 256)时,您将得到 215,当解释为带符号的 8 位数字时为 -41 (215 + 41 = 256 = 28)。
对 Byte 类型进行签名的选择引起了很多批评,因为它为基本序列化操作增加了很多微妙之处,对此人们通常更喜欢 int 类型很有道理。
Java only knows signed types. When you truncate 32727 to 8 bits (i.e. modulo 256), you get 215, which is -41 when interpreted as a signed 8-bit number (215 + 41 = 256 = 28).
The choice of making the
Byte
type signed has caused plenty of criticism, since it adds a lot of subtlety to basic serialization operations, for which people generally prefer theint
type for this very reason.