The << and >> in C are bit shift operators, used for bitwise left shift and bitwise right shift of integers respectively. The left shift operator (<<) shifts the binary representation of an integer to the left, filling empty bits with the sign bit or 0. The right shift operator (>>) shifts the binary representation of an integer to the right, filling empty bits with the sign bit or 0.
##The difference between << and >> in C
<< in C (left shift operator) and >> (right shift operator) are bitwise operators used to shift signed or unsigned integers bitwise. The main difference between them is the direction of movement.Left shift operator (<<)
Left shift operator << Shifts the binary representation of an integer to the left by the specified number of places. When the integer is a signed integer, the vacated bits are filled with sign bits (0 for positive numbers, 1 for negative numbers); when the integer is an unsigned integer, the vacated bits are filled with 0s.Right shift operator (>>)
Right shift operator >> Shifts the binary representation of an integer to the right by the specified number of places. For signed integers, the sign bit is copied into the vacated bit, thus preserving the sign of the number. For unsigned integers, vacated bits are filled with 0s.Usage
The left shift operator is typically used to multiply an integer by a power of 2 because it is equivalent to adding 0 in the binary representation.int x = 5; // 二进制:101 x << 2; // 二进制:10100 (等效于 x * 2^2)
int y = 20; // 二进制:10100 y >> 2; // 二进制:101 (等效于 y / 2^2)
Example
The following table compares the effect of using << and >> to perform displacement operations on signed and unsigned integers:Signed integer | Unsigned integer | |
---|---|---|
5 << 2
| 2020 | |
-5 << 2
| -20-20 | |
1 |
1 | |
-2 |
2147483646 |
For unsigned integers, the result of the right shift operation is always a positive number.
The above is the detailed content of What is the difference between << and >> in c++. For more information, please follow other related articles on the PHP Chinese website!