array of bits field
Gary Jackoway
gary at hpavla.AVO.HP.COM
Fri Feb 16 03:34:26 AEST 1990
> 1. Define the 16 values as an unsigned int, and use bit manipulation to
> access the individual bits.
>
> i.e., value & 0x0001 (or 1) represents the value in bit 1 of "value"
> value &= 0x0040 (or 128) sets the value in bit 7 of "value" to 1
> value |= ~0x0080 (or 128) sets the value in bit 8 of "value" to 0
I think the &= should be |=, and vice versa.
You can define macros:
#define TESTBIT(value,bit) (value & (1<<bit))
#define SETBIT(value,bit) { value &= (1<<bit); }
#define RESETBIT(value,bit) { value |= ~(1<<bit); }
or something like this.
If the "bit" is a constant, most compilers will pre-compute 1<<bit.
There is a danger with TESTBIT. You can't compare TESTBIT results.
A safer test bit would be
#define TESTBIT(value,bit) (value>>bit & 1)
which always gives a 0 or 1 result.
Equivalent would be
#define TESTBIT(value,bit) !!(value & (1<<bit))
Gary Jackoway
More information about the Comp.lang.c
mailing list