按位移位运算符Bitwise Shift Operators

移位运算符按第二个操作数指定的位置数量向左 (<<) 或向右 (>>) 移动第一个操作数。The shift operators shift their first operand left (<<) or right (>>) by the number of positions the second operand specifies.

语法Syntax

shift-expression:shift-expression:
additive-expressionadditive-expression

shift-expression << additive-expression shift-expression >> additive-expressionshift-expression << additive-expression shift-expression >> additive-expression

两个操作数都必须是整数值。Both operands must be integral values. 这些运算符执行常用算术转换;结果的类型是转换后左操作数的类型。These operators perform the usual arithmetic conversions; the type of the result is the type of the left operand after conversion.

对于左移,留空的右位将设置为 0。For leftward shifts, the vacated right bits are set to 0. 对于右移,将根据转换后第一个操作数的类型填充留空的左位。For rightward shifts, the vacated left bits are filled based on the type of the first operand after conversion. 如果该类型为 unsigned,留空的左位将设置为 0。If the type is unsigned, they are set to 0. 否则,将使用符号位的副本填充它们。Otherwise, they are filled with copies of the sign bit. 对于没有溢出的左移运算符,语句For left-shift operators without overflow, the statement

expr1 << expr2   

等效于乘以 2expr2is equivalent to multiplication by 2expr2. 对于右移运算符,For right-shift operators,

expr1 >> expr2   

等效于除以 2expr2(如果 expr1 为无符号或具有非负值)。is equivalent to division by 2expr2 if expr1 is unsigned or has a nonnegative value.

如果第二个操作数为负,或者右操作数大于或等于提升后的左操作数的宽度(以位为单位),则移位运算的结果不确定的。The result of a shift operation is undefined if the second operand is negative, or if the right operand is greater than or equal to the width in bits of the promoted left operand.

由于没有为溢出或下溢情况提供移位运算符执行的转换,因此当移位运算的结果不能用转换后第一个操作数的类型表示时,信息可能丢失。Since the conversions performed by the shift operators do not provide for overflow or underflow conditions, information may be lost if the result of a shift operation cannot be represented in the type of the first operand after conversion.

unsigned int x, y, z;  

x = 0x00AA;  
y = 0x5500;  

z = ( x << 8 ) + ( y >> 8 );  

在此示例中,x 将向左移位 8 个位置,y 将向右移位 8 个位置。In this example, x is shifted left eight positions and y is shifted right eight positions. 移位值(假定 0xAA55)将相加并赋给 zThe shifted values are added, giving 0xAA55, and assigned to z.

将负值向右移位可生成原始值一半的值(向下舍入)。Shifting a negative value to the right yields half the original value, rounded down. 例如,-253(二进制 11111111 00000011)向右移动 1 位会生成 -127(二进制 11111111 10000001)。For example, -253 (binary 11111111 00000011) shifted right one bit produces -127 (binary 11111111 10000001). 将 + 253 向右移位生成 +126。A positive 253 shifts right to produce +126.

右移保留符号位。Right shifts preserve the sign bit. 当带符号的整数向右移位时,最高有效位将保留。When a signed integer shifts right, the most-significant bit remains set. 当无符号的整数右移位时,将清除最高有效位。When an unsigned integer shifts right, the most-significant bit is cleared.

请参阅See Also

左移和右移运算符(>> 和 <<)Left Shift and Right Shift Operators (>> and <<)