volting
volting

Reputation: 19097

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 cant seem to get them to work correctly.

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

Upvotes: 4

Views: 53633

Answers (3)

Artelius
Artelius

Reputation: 49134

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

Upvotes: 11

Michael Dorgan
Michael Dorgan

Reputation: 12515

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.

Upvotes: 0

CB Bailey
CB Bailey

Reputation: 793109

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

Upvotes: 9

Related Questions