首页 > int强制转化为byte,得到什么?

int强制转化为byte,得到什么?

int iValue = 233;
byte bValue = (byte) iValue; //int强制转化为byte
System.out.println(bValue); 

如上,输出结果是什么?为什么?


楼上都是正解,不过可以不去理解补码的概念,整数二进制表示只需要知道一点就行了,那就是:有符号数的最高位的权值需要乘以 -1,比如以下是233的32位二进制表示:
233 = 00000000 00000000 00000000 11101001
该数的最高位为0,所以其权值为0,乘以 -1 依然是0,所以整个数是正数
将其转换成为type后为:
11101001,那么该数的值就是:
-1 * 1 * 2^7 + 1 * 2^6 + 1 * 2^5 + 0 * 2^4 + 1 * 2^3 + 0 * 2^2 + 0 * 2^1 + 1 * 2^0 = -128 + 64 + 32 + 8 + 1 = -23

理解了这点后对于理解整数的二进制表示很有帮助,例如不管这个数用多少位来表示,我们都可以知道以下特点:
1. 所有位都为1时该值是 -1,因为2^0 + 2^1 + ... + 2^(n-1) = 2^n - 1。计算-1 + 1 = 0,因为其二进制表示的最高位溢出了,留下的有效位全为0,所以就自然得到了0;
2. 仅最高位为1,其余位都为0时表示最小的负数;
3. 仅最高位为0,其余位都为1时表示最大的正数。


计算机中数值都是以二进制补码的形式存储
二进制数值的第一位代表数值的符号(正数为0,负数为1)

其中正数的补码等于其原码
负数的补码等于其原码(除符号位)的反码+1

java中
int占32位
byte占8位

int 233=00000000 00000000 00000000 11101001
强转后去掉前面的24个0,得11101001

补充:补码转换为原码的规则:对该补码再次求补码

接着判断首位是1,为负数,取补码得10010110+1=>-23


楼上正确, 补一下官方文档:

jls7, 5.1.3 Narrowing Primitive Conversion

A narrowing conversion of a signed integer to an integral type T
simply discards all but the n lowest order bits, where n is the number
of bits used to represent type T. In addition to a possible loss of
information about the magnitude of the numeric value, this may cause
the sign of the resulting value to differ from the sign of the input
value.

【热门文章】
【热门文章】