Cancel bit offsets instead of expected behavior

I noticed strange behavior with bitrate using 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 it cto have a value of 1 too ... what is happening? Is it undefined?

+4
source share
5 answers

Bit-shift a charautomatically advances it to int. This is why a left shift of 7 bits does not chop off anything.

Source: Section 6.5.7 Standard C

Integer promotions are executed for each of the operands. The result type is the advanced left operand. If the value of the correct operand is negative or greater than or equal to the width of the advanced left operand, the behavior is undefined.

+4
source

int, char. char . , a char, int.

, 6.5.7 :

  • .

  • - .

  • , undefined.

+2

-, :

6.5.7

2 .

3 .

, c = (c << 7) >> 7, c (c << 7) , . , . >> 7 .

d = (d << 7), , () d, char " " .

+1

153 10011001. int, .

 c = (c << 7) >> 7; 

c 4 , c 00000000 00000000 00000000 10011001 . ,

c = (c << 7) >> 7;   // Left and right shift operator will nullify the effect of each other. 

c = c; 

d = (d << 7);
d = (d >> 7);  

d ( ) 10000000. d ( ) 00000001.

+1

, , x86 c = (c << 7) >> 7:

movzbl  31(%esp), %eax ;eax = c
sall    $7, %eax ;left shift
sarl    $7, %eax ;right shift
movb    %al, 31(%esp) ;c = al (one byte)

c 32- (eax), . , (.. al) c.

In short, both shifts are evaluated as if the operands were 32-bit.

0
source

Source: https://habr.com/ru/post/1686385/


All Articles