Search code examples
cbit-shift

C and bitwise shifts


I have probably a newby question about bitwise shifts in C. I wanted to write a macro, which will return a n-th bit of the unsigned char. My initial idea was to left shift by (7-n), bringing the bit to MSB position, and right shift by 7, bringing the bit to LSB. This didnt work, so I started with testing in non-macro enviroment.

So this doesnt work:

int main() {
    unsigned char c=126,d,i;
        
    for(i=0;i<8;++i){
        d = (c<<(7-i)) >> 7;
        printf("%d bit: %d\n",i,d);
    }
    return 0;
}

But this works:

int main() {
    unsigned char c=126,d,i;
        
    for(i=0;i<8;++i){
        d = (c<<(7-i));
        d >>= 7;
        printf("%d bit: %d\n",i,d);
    }
    return 0;
}

I solved the original problem with &mask.. d=(c>>i)&1;. However, I still dont understand why are those two different... Any ideas?


Solution

  • With unsigned char c=126 and i==0:

    (c<<(7-i)) is a 14-bit value.

    d = (c<<(7-i)) >> 7; retains that 14-bit value then shifts right 7: information preserved.

    d = (c<<(7-i)); d >>= 7; truncates that 14-bit value to 8-bits when saved into d, then shifts right: information lost.