-1 和 ~0 有什么区别
标题确实说明了一切:负一和蒂尔达(补码)零有什么区别?
这个问题是在讨论指定设置所有位的位掩码的最佳方法时出现的。以下哪个更好?
int func(int value, int mask = -1) {
return (value & mask);
}
或者
int func(int value, int mask = ~0) {
return (value & mask);
}
是否还有其他用途,但情况恰恰相反?
更新:在 stackoverflow.com/q/809227/34509 上有关于这个主题的类似讨论,我在其中错过了我之前的研究。感谢约翰内斯·绍布指出这一点。
The title really says it all: what is the difference between minus one and tilda (ones-complement) zero?
The question came up during a discussion of the best way to specify a bit mask in which all bits are set. Which of the following is better?
int func(int value, int mask = -1) {
return (value & mask);
}
or
int func(int value, int mask = ~0) {
return (value & mask);
}
Are there any other uses where it would be the other way around?
Update: There has been a similar discussion on this topic over at stackoverflow.com/q/809227/34509 which I missed during my prior research. Thanks to Johannes Schaub for pointing it out.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
第一个变体依赖于负数的 2 补码表示,但不一定使用。也可以使用 1 的补码...或其他编码。我投票支持第二种方法
The first variant relies on 2's complement representation of negative numbers, which isn't necessarily used. 1's complement can be used too... or other encoding. My vote is for the second approach
第二个例子更清楚地说明您要测试的内容。
The second example is more clear as to what you're trying to test for.
两者都是一样的。除此之外,
-1
与unsigned int
配合得很好,不会出现警告。Both are same. Except that,
-1
doesn go well withunsigned int
without warning.