Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does '<<' mean in C?

what does this mean?

#define WS_RECURSIVE    (1 << 0)

I understand that it will define WS_Recursive (1 << 0) but what does << mean?

Thanks!

like image 252
Charlie Avatar asked Nov 27 '22 04:11

Charlie


1 Answers

<< 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

like image 78
Seth Carnegie Avatar answered Dec 21 '22 01:12

Seth Carnegie