按位左移行为 [英] Bitwise left shift behaviour

查看:133
本文介绍了按位左移行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我正在学习左移位操作符(<< )。据我所知,左移位操作符按指定向左移动位。而且我知道转移乘以2。但我很困惑,就像移位究竟是什么意思一样,为什么当用不同的类型赋值时输出会有所不同?

Today I was learning about the left shift bit operator (<<). As I understand it the left shift bit operator moves bits to the left as specified. And also I know multiply by 2 for shifting. But I am confused, like what exactly is the meaning of "shifting bits" and why does the output differ when value is assigned with a different type?

当我打电话给在下面的函数中,它输出为 System.out.println(b =+ b); //输出:0

When I call the function below, it gives output as System.out.println("b="+b); //Output: 0

我的问题是:b如何变为0以及为什么b被类型化?

And my question is: how does b become 0 and why is b typecasted?

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
}






更新(新疑问):

这是什么意思如果你将1位移到高位(位31或63),价值将变为负面。例如。

what does it mean "If you shift a 1 bit into high-order position (Bit 31 or 63), the value will become negative". eg.

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中转换为字节时,只保留最低位:

When integers are casted to bytes in Java, only the lowest order bits are kept:


签名的缩小转换整数到整数类型T
只丢弃除n个最低位之外的所有位,其中n是用于表示类型T的位数
。除了可能丢失
之外的信息数值的大小,这可能导致
结果值的符号与输入
值的符号不同。

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 具有以下二进制表示形式:

In this case the byte 64 has the following binary representation:

01000000

移位运算符将值提升为int:

The shift operator promotes the value to int:

00000000000000000000000001000000

然后左移2位:

00000000000000000000000100000000

然后我们将其转换回一个字节,因此我们丢弃除最后8位之外的所有位:

We then cast it back into a byte, so we discard all but the last 8 bits:

00000000

因此,最终字节值为 0 。但是,您的整数保留所有位,因此它的最终值确实是 256

Thus the final byte value is 0. However, your integer keeps all the bits, so its final value is indeed 256.

这篇关于按位左移行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆