SparkFun Forums 

Where electronics enthusiasts find answers.

Your source for all things Atmel.
By kacper
#121407
Hi,

I have a question that has been bugging me for a while. What's the difference between
Code: Select all
PORTD &= ~(1 << bit)
and
Code: Select all
port &= (0 << bit)
. Maybe there is no difference? :roll:
By fll-freak
#121410
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.
By qema
#121663
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