我正在学习 Primer 5th edition 中的 C++。其中一个问题是:
What is the value of ~'q' << 6 on a machine with 32-bit ints and 8 bit chars, that uses Latin-1 character set in which 'q' has the bit pattern 01110001?
我感到困惑的是,编译器会在 ~ 之前或 < 之前将 'q' 转换为 32 位 int
据我了解它应该是这样工作的:
'q' = 01110001
~'q' = 10001110
~'q' << 6 = 00000000000000000010001110000000
我说的对吗?
最佳答案
运算符 ~
对其操作数执行整数提升(C++11,[expr.unary.op]§10
)。这意味着它会在进行补码之前将 char
转换为 int
。所以它会像这样:
'q' == 01110001
~ 'q' == ~ 00000000000000000000000001110001
~ 'q' == 11111111111111111111111110001110
那么问题来了。我们看到 ~ 'q'
的值是负数。左移负值具有未定义的行为 ([expr.shift]§2
)。 (感谢 @colombien's answer 指出最后一部分)
关于C++ NOT位运算符二进制char转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19585507/