c++ - How to write new value to individual bit without (if/else) operator -


i know can set bit n by:

value |= 1 << n; 

or clear bit n by:

value &= ~(1 << n); 

but efficient way "write" (not set or clear) bit n? example, have function:

__inline void writebit(char &value, int n, bool state) {     if(state)         value |= 1 << n;     else         value &= ~(1 << n); } 

can somehow rid of if/else statements , instead using binary , shift operators?

the page of bit hacks suggests using following formula:

value ^= (-state ^ value) & (1 << n); 

the declaration of state needs change bool int.

this trick works on computers twos complement representation of negative numbers, because unary minus -state changes state 1 number composed of ones, , leaves 0 unchanged.

an alternative superscalar cpus looks this:

value = (value & ~(1 << n)) | (-state & (1 << n)); 

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -