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?
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?
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.
a<<b for integers means "shift left". The bitwise representation of a is shifted left b bits. This is the same as multiplying by (2 to the power of b).
So in your example, (1<<1) is 1*(2^1) is 2, (1<<8) is 1*(2^8) is 256.
It is worth pointing out that in general, as with other operators in c++, << may be overridden to perform other functions. By default, input/output streams override this operator to let you write concise code to send a bunch of parameters to the stream. So you may see code like this:
cout << something << somethingelse
and << does not mean left shift in this context.
<< is bitwise shift left (there is also >> bitwise shift right)
if you have 32 bit integer
1 = 00000000 00000000 00000000 00000001 = 1
1 << 1 = 00000000 00000000 00000000 00000010 = 2
1 << 8 = 00000000 00000000 00000001 00000000 = 256
Those are bitwise shift operators.
http://msdn.microsoft.com/en-us/library/336xbhcz(v=vs.80).aspx
<< is shifting left so it is actually multiplying by 2 for << 1 and by 2^8 for << 8.
The operator << is a bitwise left-shift operator.
So when you write 1<<17, the binary representation of 1 is shifted left by 17 bits as:
//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)
a<<b means (a * pow(2,b))-> a * 2^b //left-sift operator <<
a>>b means (a / pow(2,b))-> a / 2^b //right-sift operator >>
1<<8
here is how i understood it. in the most layman way, understand it as 1 (00000001) in binary number system is now promoted to the 8 places(bits) ahead from where it was earlier, and for every place as we know it moves the value(2 in binary) gets exponentially multiplied so it becomes 1*(2^8)=256.
so 1<<6 will be 1*(2^6)= 64 and so on