返回信息流uint64_t flag = 0x123456789abcdef0
// 判断x的右数第i个比特(i=0,1,2,3,...,63)是否是1.
bool is_set(uint64_t x, int i) {
return (x & (1 << i)) != 0;
}
int main() {
bool result = is_set(flag, 35); // 有时候会是false,为什么呢?明明35对应的是8里面的那个1啊。
}
这是一条镜像帖。来源:北邮人论坛 / cpp / #88963同步于 2015/10/3
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖
C语言也惊喜:我的比特呢?
nuanyangyang
2015/10/3镜像同步21 回复
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
"1" has a signed type and non-negative value, but 1*2^35 is not representable in the result type.
所以结论还是undfined behavior。
【 在 nuanyangyang 的大作中提到: 】
: [code=c]
: uint64_t flag = 0x123456789abcdef0
: // 判断x的右数第i个比特(i=0,1,2,3,...,63)是否是1.
: ...................
【 在 xiaobing307 的大作中提到: 】
: 不懂,因为1是int?
: 来自「北邮人论坛手机版」
倒不是1是int,而是i是int。
【 在 caesar11 的大作中提到: 】
: [upload=1][/upload]
: "1" has a signed type and non-negative value, but 1*2^35 is not representable in the result type.
: 所以结论还是undfined behavior。
恭喜你抓住了鼻子里的恶魔
【 在 glazard 的大作中提到: 】
: 是因为 arithmetic promotion 吧,内层括号已经溢出了,或者说 promotion 不是默认提升到64位
嗯。内层括号里,1只是视为int,先溢出了,然后再promote到long,于是就有问题了。