What is going on with bitwise operators and integer promotion?

后端 未结 4 1550
别跟我提以往
别跟我提以往 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:12

    I tested larger numbers and operator << always gives me positive numbers, while operator ~ always gives me negative numbers. I then used sizeof() and found...

    Wrong, test it:

    uint8_t v = 1;
    for (int i=0; i<32; i++) cout << (v<

    gives:

    1
    2
    4
    8
    16
    32
    64
    128
    256
    512
    1024
    2048
    4096
    8192
    16384
    32768
    65536
    131072
    262144
    524288
    1048576
    2097152
    4194304
    8388608
    16777216
    33554432
    67108864
    134217728
    268435456
    536870912
    1073741824
    -2147483648
    

    uint8_t is an 8-bit long unsigned integer type, which can represent values in the range [0,255], as that range in included in the range of int it is promoted to int (not unsigned int). Promotion to int has precedence over promotion to unsigned.

提交回复
热议问题