What is going on with bitwise operators and integer promotion?

后端 未结 4 1545
别跟我提以往
别跟我提以往 2020-11-28 15:32

I have a simple program. Notice that I use an unsigned fixed-width integer 1 byte in size.

#include 
#include 

        
4条回答
  •  执念已碎
    2020-11-28 16:29

    Look into two's complement and how computer stores negative integers.
    Try this

    #include 
    #include 
    #include 
    int main()
    {
    uint8_t x = 1;
    int shiftby=0;
    shiftby=8*sizeof(int)-1;
    std::cout << (x << shiftby) << '\n'; // or std::cout << (x << 31) << '\n';
    
    std::cout << ~x;
    
    std::cin.clear();
    std::cin.ignore(std::numeric_limits::max(), '\n');
    std::cin.get();
    return 0;
    }
    

    The output is -2147483648

    In general if the first bit of a signed number is 1 it is considered negative. when you take a large number and shift it. If you shift it so that the first bit is 1 it will be negative

    ** EDIT **
    Well I can think of a reason why shift operators would use unsigned int. Consider right shift operation >> if you right shift -12 you will get 122 instead of -6. This is because it adds a zero in the beginning without considering the sign

提交回复
热议问题