Unexpected output when executing left-shift by 32 bits

前端 未结 2 1117
情歌与酒
情歌与酒 2020-12-11 12:56

When I do a left shift of a hex I get -1 as output with the following code:

unsigned int i,j=0;
i= (0xffffffff  << (32-j));
printf(\"%d\",i);


        
相关标签:
2条回答
  • 2020-12-11 13:29

    Shifting a 32-bit variable by 32 yields undefined behavior.

    Here is the assembly generated by the VS-2013 compiler:

        int n = 0;
    mov         dword ptr [n],0  
        int a = 0xFFFFFFFF << 32;
    mov         dword ptr [a],0  
        int b = 0xFFFFFFFF << (32-n);
    mov         ecx,20h  
    sub         ecx,dword ptr [n]  
    or          eax,0FFFFFFFFh  
    shl         eax,cl  
    mov         dword ptr [b],eax  
    

    As you can see, what happens de-facto is:

    • When you shift by a constant value of 32, the compiler simply sets the result to 0
    • When you shift by a variable (such as 32-n with n==0), the compiler uses shl

    The actual result of shl depends on the implementation of this operation in the underlying architecture. On your processor, it probably takes the 2nd operand modulo 32, hence the 1st operand is shifted by 0.

    Again, the description above is not dictated by the standard, so it really depends on the compiler in use.

    0 讨论(0)
  • 2020-12-11 13:42

    It's undefined behavior to left-shit 32 or greater on a 32-bit integer. That's what the error is about.

    C11 6.5.7 Bitwise shift operators

    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.

    0 讨论(0)
提交回复
热议问题