opu 웃
opu 웃

Reputation: 462

Shifting a byte value

I have following java program:

public class java {


    public static void main(String[] args) {

        byte a=64, b;
        int i;

        i=a<<2;
        b=(byte)(a<<2);

        System.out.println(i);
        System.out.println(b);

    }

}

In this program, how the value of b is zero? I didn't get it.

Upvotes: 0

Views: 49

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201517

Because a byte is exactly 8 bits. And the last 8 bits of your int are 0. If we add the result of Integer.toBinaryString(int) like,

byte a = 64;
int i = a << 2;
System.out.println(Integer.toBinaryString(i));
byte b = (byte) (a << 2);

you'll see that the output is

100000000

so b (because the 1 is the ninth bit) becomes

00000000

(which is 0).

Upvotes: 3

Related Questions