foreword
We all know that for signed data types, the leftmost digit of the binary is the sign bit, 0 represents positive, 1 represents negative, here are a few concepts
Logical left shift = arithmetic left shift: high-order overflow, low-order fill with 0
Logical right-shift: low-order overflow, high
-order fill with 0
For example, a signed 8-bit binary number 10101010, [] is the added number
Logical shift left by one bit: 0101010[0]
Logical shift left by two bits: 101010[00]
Arithmetic shift left by one: 0101010[0]
Arithmetic shift left by two: 101010[00]
Logical shift right one bit: [0]1010101
Logical shift right two bits: [00]101010
Arithmetic shift right by one: [1] 1010101
Arithmetic shift right by two: [11] 101010
Arithmetic left shift and arithmetic right shift are mainly used to multiply and halve signed numbers.
Logical left shift and logical right shift are mainly used to multiply and halve unsigned numbers
(there is no unsigned data type in Java, C and in C++)
symbol | example | explain |
---|---|---|
<< | num<< n | equivalent to , arithmetic left shift (logical left shift) |
>> | num>>n | equivalent to , arithmetic shift right |
>>> | num>>>n | logical right shift, when num is positive and arithmetic right shift an effect |
public static void main(String[] args) {
// 20
System.out.println(10 << 1);
// -20
System.out.println(-10 << 1);
// 5
System.out.println(10 >> 1);
// -5
System.out.println(-10 >> 1);
// 5
System.out.println(10 >>> 1);
// 2147483643
System.out.println(-10 >>> 1);
}
Reference blog
[1]https://blog.csdn.net/coffeelifelau/article/details/52433653
[2]https://www.cnblogs.com/yongdaimi/p/5945114.html
[3]https://www.cnblogs.com/hongten/p/hongten_java_yiweiyunsuangfu.html
[4]https://jingyan.baidu.com/article/5552ef47e5618d518ffbc9db.html
[5]https://wenku.baidu.com/view/35f45e711711cc7931b716ef.html
[6]https://zhidao.baidu.com/question/318471799.html
[7]https://www.cnblogs.com/ylz8401/p/6858020.html