java - 按位左移行为

标签 java bitwise-operators

今天我学习了左移位运算符 ( << )。据我了解,左移位运算符按指定将位向左移动。而且我还知道乘以 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/

相关文章:

c - 取 C 中半字节的最后 2 位

java - 如何强制运行未签名的java应用程序

php - Xoring PHP 中的两个字符?

php - 什么时候应该使用按位运算符?

java - HBase alter table 命令失败并显示 "ERROR: d != java.lang.String"

在 C 中将 int 转换为 float(无转换)

java - Java 中按位运算符对 boolean 值的影响

java - 无法实例化 Android 驱动程序 appium 1.8.1

java - 查找算术级数中缺失的项 -

java - 使用 JPA native 查询时是否必须选择所有实体属性?