How to set certain bits of unsigned short

Hey,
I have a double variable and depending on certain conditions I need to set certain bits of an unsigned short Variable. For example, if double var is odd I need to set the 15th bit of the unsigned short variable. I am a little clueless on how to do this, can anyone give me some input in how to do this.
Thanks In Advance
Assuming the 15th bit is counted starting from 1.
1
2
usVar = 0;
usVar |= 1 << 14


By the way, how do you check if a double is odd? Do you check only the integral part?
Last edited on
Thanks for the example. By any chance, can you explain what that code is doing? Oh yeah, I am not checking to see if num is odd was just giving an example. I am checking to see if it is divisible by 200.
Thanks
The first line simply sets all the bits of usVar to 0.

The second line is equivalent to
usVar = usVar | (1 << 14); // parentheses because I don't remember operator precedence

<< is the "left shift" operator. It moves the bits representing a value by a number of places specified by the number on the right.
For example let's do 7 << 2
7 = 00000111
Moving the bits to the left by 2 places yields 00 | 00011100. The leftmost bits are lost, and the hole is filled with 0s.
Now, 1 = 00000001. You can see that only the first bit is on. Left-shifting by N means that you will turn on only one bit, the one N positions away from the rightmost bit, and the first bit will be left with a 0. This allows you to turn on a specific bit, and to turn on that bit for another value you use the bitwise OR.

| is the bitwise OR operator. You need to know some boolean algebra here; if you do you can easily understand that
1
2
3
4
usVar = 00000000 OR
1<<5  = 00100000 
       ____________
        00100000

you turned on the 5th bit of usVar. (counting from 0, or 6th from 1)

I used 8 bits for simplicity.
Important note: bit shifting is relatively easy with unsigned types, which use logical shift. For signed types it's more complex, they use arithmetic shift.

http://en.wikipedia.org/wiki/Logical_shift
http://en.wikipedia.org/wiki/Arithmetic_shift
Last edited on
Thanks so much!! Fully understand.
Topic archived. No new replies allowed.