B
Ben C
Hi,
Can anyone please tell me how to toggle a nth bit. For example, I am
having a variable which is of 8 bits. I want to toggle the nth bit.
var ^= (1U << n);
should do it
Sometimes you see flags done like this:
uint32_t set_flags(uint32_t flags, uint32_t clear, uint32_t xor)
{
return (flags & ~clear) ^ xor;
}
This odd-looking function allows you to set, toggle and clear any
combination of flags in one go, as the example below illustrates a bit.
Whether this is more or less confusing I'm not sure... it's quite good
in APIs, though, where the fact that flags are stored as bits is not
necessarily exposed to the caller.
#include <stdio.h>
#include <stdint.h>
uint32_t set_flags(uint32_t flags, uint32_t clear, uint32_t xor)
{
return (flags & ~clear) ^ xor;
}
#define APPLES 1U
#define PEARS 1U << 1
#define ORANGES 1U << 2
#define BANANAS 1U << 3
void print_flags(uint32_t flags)
{
if (flags & APPLES) printf("APPLES\n");
if (flags & PEARS) printf("PEARS\n");
if (flags & ORANGES) printf("ORANGES\n");
if (flags & BANANAS) printf("BANANAS\n");
printf("\n");
}
int main(void)
{
uint32_t flags = APPLES | ORANGES;
print_flags(flags);
/* set PEARS */
flags = set_flags(flags, PEARS, PEARS);
print_flags(flags);
/* clear PEARS */
flags = set_flags(flags, PEARS, 0);
print_flags(flags);
/* toggle PEARS a couple of times */
flags = set_flags(flags, 0, PEARS);
print_flags(flags);
flags = set_flags(flags, 0, PEARS);
print_flags(flags);
/*
* set BANANAS, toggle PEARS and APPLES, and clear ORANGES, all in one go
*/
flags = set_flags(flags, ORANGES | BANANAS, BANANAS | PEARS | APPLES);
print_flags(flags);
return 0;
}