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)))
3 个解决方案
#1
8
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);
}
#2
7
One obvious issue is that ((p) &= (~(1) << (n)))
should be ((p) &= ~(1 << (n)))
.
一个显而易见的问题是,((p)& =(~(1)< <(n)))((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)))
除此之外,您必须注意整型类型的宽度。如果使用无符号长,可能需要使用(例如)(p) |= (1UL < (n)))
#3
0
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.
如果失败了,上述的失败又如何呢?它们看起来“还行”,但如果函数不可用,我还是宁愿手工操作。当执行此类操作时,宏只会隐藏令人讨厌的bug。传递有符号的和无符号的,等等不会被宏捕获。
#1
8
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);
}
#2
7
One obvious issue is that ((p) &= (~(1) << (n)))
should be ((p) &= ~(1 << (n)))
.
一个显而易见的问题是,((p)& =(~(1)< <(n)))((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)))
除此之外,您必须注意整型类型的宽度。如果使用无符号长,可能需要使用(例如)(p) |= (1UL < (n)))
#3
0
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.
如果失败了,上述的失败又如何呢?它们看起来“还行”,但如果函数不可用,我还是宁愿手工操作。当执行此类操作时,宏只会隐藏令人讨厌的bug。传递有符号的和无符号的,等等不会被宏捕获。