Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitshifts canceling out instead of expected behavior [duplicate]

I noticed some strange behavior with bitshifting with brackets

 #include <stdio.h>

int     main(void)
{
    unsigned char c;
    unsigned char d;

    c = 153;
    c = (c << 7) >> 7;
    printf("%d\n", c);
    d = 153;
    d = (d << 7);
    d = (d >> 7);
    printf("%d\n", d);
}

output:

153
1

I expected c to also have a value of 1... whats going on? Is this undefined?

like image 853
Theo Walton Avatar asked Jan 30 '23 12:01

Theo Walton


1 Answers

Bit-shifting a char automatically promotes it to an int. This is why a left shift of 7 bits doesn't chop anything off.

Source: section 6.5.7 of the C standard

The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.

like image 51
Charles Srstka Avatar answered Feb 01 '23 08:02

Charles Srstka