C++ - Bit-wise not of uchar produces int

后端 未结 3 1815
感情败类
感情败类 2021-01-05 09:54

I am surprised by C++\'s behavior when applying bit-wise not to an unsigned char.

Take the binary value 01010101b, which is 0x55, or

3条回答
  •  佛祖请我去吃肉
    2021-01-05 10:38

    You can kind of "truncate" the leading 1's by assigning the result of ~0x55 to an unsigned char:

    #include 
    
    int main()
    {
        unsigned char input = 0x55;
        unsigned char output = ~input;
    
        std::cout << "input: " << (int)input << " output: " << (int)output << std::endl;
    
        return 0;
    }
    

    Result:

    input: 85 output: 170
    

提交回复
热议问题