What does '<<' mean in C?

前端 未结 5 1879
一生所求
一生所求 2021-01-07 08:33

what does this mean?

#define WS_RECURSIVE    (1 << 0)

I understand that it will define WS_Recursive (1 << 0) but w

5条回答
  •  别那么骄傲
    2021-01-07 09:14

    << is the left shift operator. It is shifting the number 1 to the left 0 bits, which is equivalent to the number 1.

    It is commonly used to create flags, numbers that can be combined together with | (bit or) and various operations can be applied to them, such as testing whether a flag is set, setting a flag, removing a flag, etc.

    The reason that they can be combined together without interfering with each other is that each one is a power of two, and that is the reason for using 1 << x, because that yields powers of two:

    1 << 0 == 20 == 1 == binary 0001
    1 << 1 == 21 == 2 == binary 0010
    1 << 2 == 22 == 4 == binary 0100
    1 << 3 == 23 == 8 == binary 1000
    etc

    You can read about bit flags here: http://www.codeproject.com/KB/tips/Binary_Guide.aspx

提交回复
热议问题