# Thread: << operator and the minus before brackets

1. ## << operator and the minus before brackets

#define MYCONSTANT -( ((MYID + 1) << 5 ) + 1 )

What is the purpose of the minus behind the brackets?

What is actually going on the red?

2. the minus sign returns the negative of everything in brackets

the << multiplies the number on the left by two to the power of the number on the right.

Ex 1.

5 << 3 = 5 * (2 to the third)

Ex 2.

3 << 5 = 3 * (2 to the power of five)

a >> would divide

3. Thanks. Useful to know. What is computationally faster to multiply '*' or '<<' ?

4. << is much faster when multiplying by a power of 2

5. ## ..

Originally Posted by Brad0407
<< is much faster when multiplying by a power of 2
I think that's compiler dependant nowadays since most compilers optimize your code to perform better. MS's compilers do for one, but check your compiler to be sure. One example that comes to mind is; I was doing a GDI render in a loop once in one of my projects and I was using multiplication by two's and everything went as expected - smooth,.. but when I changed it to the leftshift operator you could literally - visually - tell the difference in the rendering being done. The leftshift OP was slower by a couple seconds.

I think you really shouldn't have to worry about optimizing your code with Bitwise Operators because eventually, or most likely, your compiler knows what's best and will do the optimization for you, and probably better.

6. Not really. A decent compiler knows how to optimize it for you, so there really isn't any speed gain any more with it. Its real purpose is for setting and unsetting of specific bits.

There's a FAQ entry on bitwise operators if you're so inclined.

 Curses, foiled again. [/edit]

Quzah.

7. quzah's right.

The << is most commonly used for bit shifting.

Ex 1.

00001101 << 2 = 00110100

Ex 2.
01110100 >> 1 = 00111010

There's a pair of examples for you.

You can then set specific bits with the & and | operators.

Ex. 1 force the third bit to be 1
(00001011 & (1 << 3)) = 00001111

Ex. 2 force the fourth bit to be zero
(00011011 | (255 - (1 << 4)) = 00010011

Hope that clearifies a few things.

8. Thanks for all your informative responses. I will certainly consult my compiler.

example:

var1.var2.var3 |= (1<<3)

I understand the above sets the 3rd bit (litte endian) to one. How is this working exactly?

Popular pages Recent additions