What are bitwise shift (bit-shift) operators and how do they work?

后端 未结 11 1473
生来不讨喜
生来不讨喜 2020-11-21 04:46

I\'ve been attempting to learn C in my spare time, and other languages (C#, Java, etc.) have the same concept (and often the same operators) ...

What I\'m wondering

11条回答
  •  太阳男子
    2020-11-21 05:02

    The bitwise shift operators move the bit values of a binary object. The left operand specifies the value to be shifted. The right operand specifies the number of positions that the bits in the value are to be shifted. The result is not an lvalue. Both operands have the same precedence and are left-to-right associative.

    Operator     Usage
    
     <<           Indicates the bits are to be shifted to the left.
    
     >>           Indicates the bits are to be shifted to the right.
    

    Each operand must have an integral or enumeration type. The compiler performs integral promotions on the operands, and then the right operand is converted to type int. The result has the same type as the left operand (after the arithmetic conversions).

    The right operand should not have a negative value or a value that is greater than or equal to the width in bits of the expression being shifted. The result of bitwise shifts on such values is unpredictable.

    If the right operand has the value 0, the result is the value of the left operand (after the usual arithmetic conversions).

    The << operator fills vacated bits with zeros. For example, if left_op has the value 4019, the bit pattern (in 16-bit format) of left_op is:

    0000111110110011
    

    The expression left_op << 3 yields:

    0111110110011000
    

    The expression left_op >> 3 yields:

    0000000111110110
    

提交回复
热议问题