Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: what does (a<<b) mean?

Tags:

c++

operators

I have a C++ header file that contains the following definitions:

#define CACHE_NUM_WAYS    (1<<1)
#define CACHE_DATA_SIZE   (1<<8)

It is used as an integer in the rest of the code.

What does it mean? And what is its value?

like image 385
itamar Avatar asked Jun 11 '12 15:06

itamar


1 Answers

1 << 1 means:

00000000 00000001 changes to 00000000 00000010

1 << 8 means:

00000000 00000001 changes to 00000001 00000000

It's a bit shift operation. For every 1 on the right, you can think of yourself as multiplying the value on the left by 2. So, 2 << 1 = 4 and 2 << 2 = 8. This is much more efficient than doing 1 * 2.

Also, you can do 4 >> 1 = 2 (and 5 >> 1 = 2 since you round down) as the inverse operation.

like image 160
John Humphreys Avatar answered Oct 09 '22 13:10

John Humphreys