C bitwise operations

Hi,

I have a question that has been bugging me for a while. What’s the difference between

PORTD &= ~(1 << bit)
``` and ```
port &= (0 << bit)
```. Maybe there is no difference? :roll:

The first difference is the first line you are modifying ‘PORTD’ and the second ‘port’. But I do not think that is what you want.

The “<<” operator is the left shift operator. The left argument is the base value and the right operator is the number of bits to shift the base value to the left by.

0<<4 will shift the value 0 four bits to the left giving you zero

1<<4 will shift the value 1 four bits to the left giving you binary 10000b or 0x10hex or 16 decimal.

A more revealing example is:

v-----same-------v vv- zero filled

10100101b << 2 = 10010100b. The two left most bits of the source shift out and drop into the bit bucket. That creates two holes on the right that get filled with zero.

The short answer:

~(1 << 2) = ~00000100 = 11111011

but ( 0 << 2) will create 00000000

if you AND (&) by a 0 you will get a 0, so (0<<bit) will set the register to all 0’s.

I have some tutorials about the subject on my site that shows the math in details.

https://sites.google.com/site/qeewiki/b … e-bit-math