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

I have a C ++ header file containing 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?

+6
source share
5 answers

1 <1 means:

 00000000 00000001 changes to 00000000 00000010 

1 <8 means:

 00000000 00000001 changes to 00000001 00000000 

This is a small shift operation. For each 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 1 * 2.

In addition, you can do 4 โ†’ 1 = 2 (and 5 โ†’ 1 = 2 from the moment of rounding down) as an inverse operation.

+16
source

These are bitwise shift operators.

http://msdn.microsoft.com/en-us/library/336xbhcz(v=vs.80).aspx

<<moves to the left, so it is actually multiplied by 2 for <1 and 2 ^ 8 for <8.

+5
source

<< bitwise left shift (there is also >> bitwise right shift) if you have a 32-bit integer

 1 = 00000000 00000000 00000000 00000001 = 1 1 << 1 = 00000000 00000000 00000000 00000010 = 2 1 << 8 = 00000000 00000000 00000001 00000000 = 256 
+3
source

The operator << is a bitwise left-shift operator.

Therefore, when you write 1<<17 , the binary representation of 1 shifts to the left by 17 bits as follows:

 //before (assume 1 is represented by 32-bit) 1 << 17 0000 0000 0000 0000 0000 0000 0000 0001 << 17 (before - binary representation) //after 0000 0000 0000 0010 0000 0000 0000 0000 (after - binary representation) 
+2
source

a<<b for integers means left shift. The bit representation of a shifted to the left b bits. This is the same as multiplying by (2 by power b ).

So, in your example (1<<1) there is 1*(2^1) is 2 , (1<<8) is 1*(2^8) is 256 .

It is worth noting that, like other operators in C ++, << can be overridden to perform other functions. By default, I / O streams override this statement so that you can write compressed code to send a bunch of parameters to the stream. So you can see this code:

 cout << something << somethingelse 

and << does not mean left shift in this context.

+1
source

Source: https://habr.com/ru/post/917810/


All Articles