[英]What is the difference between -1 and ~0
The title really says it all: what is the difference between minus one and tilda (ones-complement) zero?标题确实说明了一切:减一和tilda(补码)零有什么区别?
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.更新:在stackoverflow.com/q/809227/34509上对此主题进行了类似的讨论,我在之前的研究中错过了这些讨论。 Thanks to Johannes Schaub for pointing it out.
感谢 Johannes Schaub 指出这一点。
The first variant relies on 2's complement representation of negative numbers, which isn't necessarily used.第一个变体依赖于负数的 2 的补码表示,这不一定是使用的。 1's complement can be used too... or other encoding.
也可以使用 1 的补码……或其他编码。 My vote is for the second approach
我的投票是第二种方法
The second example is more clear as to what you're trying to test for.第二个示例更清楚地说明了您要测试的内容。
Both are same.两者都是一样的。 Except that,
-1
doesn go well with unsigned int
without warning.除此之外,
-1
不会 go 与unsigned int
没有警告。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.