Search code examples
javaclogicunsigned

How does this work? x<<=3 = -8 where (byte)x = 127?


Why I am getting this output ?

Byte x ; x = 127; x<<=3;//same as x = x <<3 println(x)

output : -8

When i note down it in paper and twiddled the bits I was getting - 11111000 and that is = 248?

I suppose Byte occupies 1 byte (8 bits) .Dont know whether it is signed or unsigned?I assuem it to be signed?

because the given below code in C gave me -8 as well:

signed char x = 127; x<<=3; printf("the values of x = %d \n " , x);

Why -8?? rgd softy


Solution

  • It's because byte is a signed data type which uses two's complement. And 248-256 is equal to -8.