【发布时间】:2014-02-11 10:47:59
【问题描述】:
我知道 java Byte 有 8 位内存,即从 -128 到 127。我也知道窄化铸造的概念。并且 int 失去了一些精度。但是有人可以帮助我理解以下内容
public class PrimitiveTypes {
public static void main(String[] args) {
Byte byteVar= (byte) 128;
System.out.println(byteVar);
}
}
o/p is -128
请不要告诉我,因为 127 的循环它显示 -128 。 我需要这里发生的二进制算术。 我能从net找到的是java将整数存储在2的补码中,用于存储负数。 所以从 2 的补码
128 变成 10000000
after flipping 11111111
添加 1 位将是
10000000
问题是这10000000 变成-128?
回答:
谢谢我的回答:
我需要将 2 的补码 10000000 转换为十进制,如
you first check if the number is negative or positive by looking at the sign bit. If it is positive, simply convert it to decimal. If it is negative, make it positive by inverting the bits and adding one. Then, convert the result to decimal. The negative of this number is the value of the original binary.
Interpret 11011011 as a two's complement binary number, and give its decimal equivalent.
First, note that the number is negative, since it starts with a 1.
Change the sign to get the magnitude of the number.
1 1 0 1 1 0 1 1
¬ 0 0 1 0 0 1 0 0
+ 1
0 0 1 0 0 1 0 1
Convert the magnitude to decimal: 001001012 = 25_16 = 2×16 + 5 = 37_10.
Since the original number was negative, the final result is -37.
所以在我的情况下 10000000 变成 01111111 加 1 将是 10000000 这是128 原来的 no 是负数,因为第一位是 1 所以 -128
【问题讨论】:
-
你说
o/p is -128,你问“为什么是-127”。 -
真的不清楚你的问题是什么,说实话...... 128 确实是二进制的 10000000,当被视为 8 位 2 的补码时是 -127 .
-
对于一个字节 -(-128) == -128。 0111_1111 = 127, 1000_001 = -127
-
那么您的实际问题是什么?你能大声说清楚吗?请编辑问题,而不是添加评论。
-
@JonSkeet
10000000在 2 的补码中是 -128 :)
标签: java