-4

I was working on some bitwise manipulation on a timer control register in Arduino and I noticed that when I want to clear the bit CS11 in the register TCCR1B then

TCCR1B &= (0<<CS11)

will not work but the following works perfectly

TCCR1B &= ~(1<<CS11)

Why does the first (0<<CS11) method not work? I found several pages explaining how to do this and the second method is always mentioned, but I did not find any explanation why the first method does not work. Thanks for your assistance!

Bert
  • 57
  • 6

2 Answers2

0

The value of (0<<CS11) is 0 (because shifting integer all of whose bits are zero also produces zero), so TCCR1B &= (0<<CS11) will make the value of TCCR1B zero. (unless some bits of the register are not writable)

On the other hand, (1<<CS11) will be an integer one of whose bits is one and the other bits are zero (unless CS11 is too large or negative) and ~(1<<CS11) will be an integer one of whose bits is zero and the other bits are one. Therefore TCCR1B &= ~(1<<CS11) will clear one bit and leave the other bits unchanged. (unless writing to bits of the register have special meanings)

MikeCAT
  • 73,922
  • 11
  • 45
  • 70
0

this short program (which you could write yourself to see what is going on) should explain what is going on.

#include <stdint.h>
#include <string.h>
#include <stdio.h>
#include <limits.h>

void printbin(unsigned x)
{
    unsigned mask = 1 << (CHAR_BIT * sizeof(mask) - 1);
    for(;mask; mask >>= 1)
    {
        printf("%c", x & mask ? '1' : '0');
    }
    printf("\n");
}

int main(void)
{
    unsigned x = ~0;

    unsigned mask;

    mask = 0 << 5;
    printbin(x); 
    printbin(mask);
    printbin(x & mask);
    printf("\n");

    mask = 1 << 5;
    printbin(x); 
    printbin(mask);
    printbin(x & ~mask);
}

and the result:

11111111111111111111111111111111
00000000000000000000000000000000
00000000000000000000000000000000

11111111111111111111111111111111
00000000000000000000000000100000
11111111111111111111111111011111

https://godbolt.org/z/qnbTce

0___________
  • 60,014
  • 4
  • 34
  • 74