gpt4 book ai didi

c++ - 为什么 -1 >> 1 是 -1 ?并且 1 >> 1 是 0!

转载 作者:IT老高 更新时间:2023-10-28 22:16:14 28 4
gpt4 key购买 nike

我有下一个代码:

std::cout << (-10 >> 1) << std::endl;
std::cout << (-9 >> 1) << std::endl;
std::cout << (-8 >> 1) << std::endl;
std::cout << (-7 >> 1) << std::endl;
std::cout << (-6 >> 1) << std::endl;
std::cout << (-5 >> 1) << std::endl;
std::cout << (-4 >> 1) << std::endl;
std::cout << (-3 >> 1) << std::endl;
std::cout << (-2 >> 1) << std::endl;
std::cout << (-1 >> 1) << std::endl;

结果是:

-5
-5
-4
-4
-3
-3
-2
-2
-1
-1

但是为什么呢?

-11111 1111(1 字节),-1 >> 1 必须是:1011 1111 而不是 -10! (我知道符号位没有移位)

有人可以向我解释这是如何工作的吗?

最佳答案

标准 5.8/3(移位运算符):

The value of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1 divided by the quantity 2 raised to the power E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined.

所以对于“为什么?”这个问题,标准答案是:为什么不。

关于c++ - 为什么 -1 >> 1 是 -1 ?并且 1 >> 1 是 0!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4308463/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com