## Using bit shifting in an equation

6 posts / 0 new
Author
Message

I'm trying to use bit shifting to accomplish fast divition by powers of 2. But I'm getting some strange behavior. For the example code below...

```uint16_t var1;
uint16_t var2;
uint16_t basevar;

basevar = 16;

var1 = basevar >> 1;
var2 = basevar >> 1;```

Will the values in var1 and var2 both equal 8? or will var1 = 8 and var2 = 4?

Is the "basevar" variable value bit shifted JUST for the purposes of the equation? Or is the value stored in "basevar" itself shifted?

Jim M., Rank amateur AVR guy.

both results will be 8, since you are not modifying basevar itself. The shifting is done on a copy of the value in basevar for the benefit of the equation at hand.

Writing code is like having sex.... make one little mistake, and you're supporting it for life.

glitch wrote:
both results will be 8, since you are not modifying basevar itself. The shifting is done on a copy of the value in basevar for the benefit of the equation at hand.

Great. Thanks glitch.

Jim M., Rank amateur AVR guy.

FYI, Most compilers will optimize constant division by powers of 2 to bitshifts for you (even when in some rare cases its not faster)

To get the behaviour you described in the original post, you could do something like this:

```uint16_t basevar;

basevar = 16;

basevar >>= 1;    // basevar = 8
basevar >>= 1;    // basevar = 4```

Michael

crwper wrote:
To get the behaviour you described in the original post, you could do something like this:

```uint16_t basevar;

basevar = 16;

basevar >>= 1;    // basevar = 8
basevar >>= 1;    // basevar = 4```

Michael

That's what I'm trying to avoid, but it's good to know I can do that if I need to.
Thanks.

Jim M., Rank amateur AVR guy.