coding style - bitwise indexing in C? -
i'm trying implement data compression idea i've had, , since i'm imagining running against large corpus of test data, had thought code in c (i have experience in scripting languages ruby , tcl.)
looking through o'reilly 'cow' books on c, realize can't index bits of simple 'char' or 'int' type variable i'd to bitwise comparisons , operators.
am correct in perception? reasonable me use enumerated type representing bit (and make array of these, , writing functions convert , char)? if so, such type , functions defined in standard library somewhere? there other (better?) approaches? there example code somewhere point me to?
thanks -
following on kyle has said, can use macro hard work you.
it possible.
to set nth bit, use or:
x |= (1 << 5); // sets 6th-from right
to clear bit, use and:
x &= ~(1 << 5); // clears 6th-from-right
to flip bit, use xor:
x ^= (1 << 5); // flips 6th-from-right
or...
#define getbit(var, bit) ((var & (1 << bit)) != 0) // returns true / false if bit set #define setbit(var, bit) (var |= (1 << bit)) #define flipbit(var, bit) (var ^= (1 << bit))
then can use in code like:
int myvar = 0; setbit(myvar, 5); if (getbit(myvar, 5)) { // }
Comments
Post a Comment