unsigned - Using bit masking to set 0 to 1 and everything else to 0 -


how use bit masking make bits in number 1 if 0, , 0 if not?

using unsigned variable:

so, if have 0000-0000, become 1111-1111. if have 0101-0110 (or 0000-0001, or 1111-1111, etc), become 0000-0000.

is possible without using conditional?

sure, it's possible:

int y = 0xff; y = ~(y & 1 | y>>1 & 1 | y>>2 & 1 | ...) - 1 

but unless academic exercise, shouldn't. if you're concerned performance, y = y != 0 faster.

explanation:

y & 1 takes first bit of number. y >> k shifts number right k bits, allowing bit y >> k & 1. | them together, results in 1 if bit set or 0 if not. subtracting 1 gives 0 if bit set, , -1 if not. binary representation of -1 1111...

shift:

1010 - y 1010 - y >> 0  101 - y >> 1   10 - y >> 2    1 - y >> 3 

take first bit:

   0 - y >> 0 & 1    1 - y >> 1 & 1    0 - y >> 3 & 1    1 - y >> 4 & 1 

or them:

   1 - 0 | 1 | 0 | 1 

negate:

0000 - 1-1 

Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -