开发者

Macros to set and clear bits

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 ca开发者_运维百科nt seem to get them to work correctly.

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


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);
}


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)))


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜