Why ( Math.Pow(2, x) & (2^y + 2^z + 2^i) ) is always return 0

Like the title, I don't understand why that expression is always true?

Here is the detail:

// x, y, z, t is always different with each other
int x = 1;
int y = 2;
int z = 3;

int total = (int)Math.Pow(2, x) + (int)Math.Pow(2, y) + (int)Math.Pow(2, z);

int t = 4; // or any number which is not x, y, z

int result = (int)Math.Pow(2, t) & total;

result is always = 0

Can someone explain it please?

Here is some example how to apply this expression into my code :P.

I have list of day of week. I want to pick a day to go out with my friend. If today is not picked, ill not go anywhere :D

Some pre-defined value:
Day: Mon-Tue-Wed-Thu-Fri-Sat-Sun
Value: 1-2-3-4-5-6-7

I will pick Mon, Tue and Fri save value into my DB.

Instead of saving {1, 2, 5}, ill save 38 (2^1 + 2^2 + 2^5).

If today is Tue, I will check like this: 2^2 & 38 = 4. 4 is # 0 so today is the day, go out.

If today is Wed, I will check like this: 2^3 & 38 = 0. So today isn't, go to bed

Jon Skeet
people
quotationmark

Think of x, y, z and t as bit positions - you're doing a bitwise & which will clear any bits which aren't set in both operands, and 2t will only have the tth bit set.

So if x, y and z are all different, 2x + 2y + 2z will have bits x, y andz set, and 2t will have bit t set... so performing a bitwise AND operation on the two results will always give 0.

Now your original claim (which didn't specify that x, y and z were different) isn't quite true, because if x and y are the same (for example) the addition can effectively give you a different bit. (Addition of integer values each of which has just a single bit set is only equivalent to bitwise-OR if the operands all have different bits set.)

For example:

int x = 2;
int y = 2;
int z = 10; // Ignore this, effectively

// 2^2 + 2^2 + 2^10 == 2^3 + 2^10
int total = (int)Math.Pow(2, x) + (int)Math.Pow(2, y) + (int)Math.Pow(2, z);

int t = 3;
int result = (int)Math.Pow(2, t) & total; // result is now 8

people

See more on this question at Stackoverflow