-1 和 ~0 有什么区别

发布于 2024-11-24 23:46:19 字数 453 浏览 7 评论 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

感性 2024-12-01 23:46:19

第一个变体依赖于负数的 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

哎呦我呸! 2024-12-01 23:46:19

第二个例子更清楚地说明您要测试的内容。

The second example is more clear as to what you're trying to test for.

微暖i 2024-12-01 23:46:19

两者都是一样的。除此之外,-1unsigned int 配合得很好,不会出现警告。

Both are same. Except that, -1 doesn go well with unsigned int without warning.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文