今天我学习了左移位运算符 ( <<
)。据我了解,左移位运算符按指定将位向左移动。而且我还知道乘以 2 进行移位。但是我很困惑,比如“移位位”的确切含义是什么,为什么当值被分配给不同的类型时输出会不同?
当我调用下面的函数时,它的输出为 System.out.println("b="+b); //Output: 0
我的问题是:b 是如何变成 0 的,为什么要对 b 进行类型转换?
public void leftshiftDemo()
{
byte a=64,b;
int i;
i=a << 2;
b=(byte)(a<<2);
System.out.println("i="+i); //Output: 256 i.e 64*2^2
System.out.println("b="+b); //Output: 0 how & why b is typecasted
}
Update(新疑惑):
“如果将 1 位移到高位(位 31 或 63),值将变为负数”是什么意思?例如。
public void leftshifHighOrder()
{
int i;
int num=0xFFFFFFE;
for(i=0;i<4;i++)
{
num=num<<1;
System.out.println(num);
/*
* Output:
* 536870908
* 1073741816
* 2147483632
* -32 //how this is -ve?
*/
}
}
最佳答案
在 Java 中将整数转换为字节时,仅保留最低位:
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.
在这种情况下,字节 64
具有以下二进制表示形式:
01000000
移位运算符将值提升为 int:
00000000000000000000000001000000
然后左移 2 位:
00000000000000000000000100000000
然后我们将它转换回一个字节,所以我们丢弃除最后 8 位以外的所有位:
00000000
因此最终的字节值为0
。但是,您的整数保留了所有位,因此它的最终值确实是 256
。
关于java - 按位左移行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19839184/