D
D
Domus2018-03-06 10:24:46
Java
Domus, 2018-03-06 10:24:46

Why does bitwise shift work like this?

I can't figure out why bitwise left shift works this way. Shouldn't we get 1100 as a result of the first operation, and 100110 as a result of the second?

String in = "32";
byte[] b = in.getBytes();

System.out.println(Integer.toBinaryString(b[0])); // 110011
byte n = (byte)(b[0]<<2);
System.out.println(Integer.toBinaryString(n)); // 11111111111111111111111110011000
byte n = (byte)(b[0]<<1); // 1100110
System.out.println(Integer.toBinaryString(n));

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Zagaevsky, 2018-03-06
@Domus

In the first case, you have an extra zero at the end. The sign has already been mentioned.
In the second - what's wrong? Where should the first unit go?

M
MaxLich, 2018-03-06
@MaxLich

In the first case, an overflow occurs, so a negative number is obtained, but in the second case, I can’t say anything right away.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question