Home >Backend Development >C++ >Usage of << and >> in c language
In C language, << and >> are bit shift operators, used to perform bit operations on integer variables: <<: left shift operator, which represents the operand in binary Moves the specified number of bits to the left, equivalent to a power of 2. >>: Right shift operator, which moves the binary representation of the operand to the right by a specified number of digits, which is equivalent to division by a power of 2. Signed right shift (>>) preserves the sign bit, while unsigned right shift (>>>) fills empty bits with zeros.
##Usage of << and >> operators in C language
In C language , << and >> are displacement operators, used to perform displacement operations on integer variables.Left shift operator (<<)##<< The operator shifts the binary representation of the operand to the left by the specified number of digits, which is equivalent to 2 is the base exponentiation operation. For example:
int x = 5; // 二进制表示:00000000 00000101 int y = x << 2; // y 的二进制表示:00000000 00010100 // 等价于:y = x * 2^2 = 5 * 4 = 20right shift operator (>>)
operator shifts the binary representation of the operand to the right by the specified number of digits, which is equivalent to For base 2 division. It can also be divided into signed right shift (>>) and unsigned right shift (>>>).
##Signed right shift (>>):
int x = -5; // 二进制表示:11111111 11111011 int y = x >> 2; // y 的二进制表示:11111111 11111100 // 等价于:y = x / 2^2 = -5 / 4 = -2
int x = 5; // 二进制表示:00000000 00000101 int y = x >>> 2; // y 的二进制表示:00000000 00000001 // 等价于:y = x / 2^2 = 5 / 4 = 1
The bit shift operator has a wide range of application scenarios, including:
Bit field operation
The above is the detailed content of Usage of << and >> in c language. For more information, please follow other related articles on the PHP Chinese website!