用于设置和清除位的宏

发布于 2024-09-04 21:17:54 字数 184 浏览 2 评论 0原文

我试图编写一些简单的宏来简化设置和清除位的任务,这应该是一个简单的任务,但我似乎无法让它们正常工作。

#define SET_BIT(p,n) ((p) |= (1 << (n)))
#define CLR_BIT(p,n) ((p) &= (~(1) << (n)))

Im trying to write a few simple macros to simplify the task of setting and clearing bits which should be a simple task however I cant seem to get them to work correctly.

#define SET_BIT(p,n) ((p) |= (1 << (n)))
#define CLR_BIT(p,n) ((p) &= (~(1) << (n)))

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

俯瞰星空 2024-09-11 21:17:54

尝试

#define CLR_BIT(p,n) ((p) &= ~((1) << (n)))

但是,由于一般宏邪恶的各种原因,我建议不要使用宏。使用内联函数并按引用传递,如下所示:

static inline void set_bit(long *x, int bitNum) {
    *x |= (1L << bitNum);
}

Try

#define CLR_BIT(p,n) ((p) &= ~((1) << (n)))

However for various reasons of general macro evil I would advise not using a macro. Use an inline function and pass by reference, something like this:

static inline void set_bit(long *x, int bitNum) {
    *x |= (1L << bitNum);
}
倾其所爱 2024-09-11 21:17:54

一个明显的问题是 ((p) &= (~(1) << (n))) 应该是 ((p) &= ~(1 < <(n)))

除此之外,您必须小心整数类型的宽度。如果您使用的是unsigned long,您可能需要使用(例如)((p) |= (1UL << (n)))

One obvious issue is that ((p) &= (~(1) << (n))) should be ((p) &= ~(1 << (n))).

Apart from that, you do have to be careful with the width of your integer types. If you were using unsigned long you might need to use (e.g.) ((p) |= (1UL << (n)))

ゝ偶尔ゞ 2024-09-11 21:17:54

啊。您本地没有一组函数来为您执行此操作吗?这将隐藏跳过单词边界时必须发生的任何魔法。

如果做不到这一点,上面的方法怎么会失败呢?它们看起来“不错”,但如果功能不可用,我仍然宁愿手动执行此类操作。在执行此类操作时,宏只会隐藏令人讨厌的错误。传递签名与未签名等。不会被宏捕获。

Ugh. Do you not have a set of functions locally to do this for you? That would hide any sort of magic that has to occur when skipping across word boundaries.

Failing that, how does the above fail? They look 'ok', but I'd still rather do this sort of thing by hand if functions aren't available. Macros just hide nasty bugs when doing this sort of thing. Passing signed vs unsigned, etc. Won't be caught with Macros.

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