Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitwise left shift behaviour

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?

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

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
}

Update (new doubt):

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?
         */
    }
}
like image 771
Dan Avatar asked Nov 07 '13 15:11

Dan


1 Answers

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

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.

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

01000000

The shift operator promotes the value to int:

00000000000000000000000001000000

then left shifts it by 2 bits:

00000000000000000000000100000000

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

00000000

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

like image 178
Zong Avatar answered Oct 04 '22 00:10

Zong