-1

I'm learning bit mask. And found and example but couldn't make it work.

I'm trying to calculate all sum combination from one array. The result should be

0 - 1 - 2 - 3 - 3 - 4 - 5 - 6

My problem is with (i & mask) should only result in {0,1} and isn't. Instead is producing.

0 - 1 - 4 - 5 - 12 - 13 - 16 - 17

        int[] elem = new int[] { 1, 2, 3 };

        double maxElem = Math.Pow(2, elem.Length);

        for (int i = 0; i < maxElem; first++)
        {
            int mask = 1, sum = 0;
            for (int run = 0; run < elem.Length; run++)
            {
                sum += elem[run] * (i & mask);
                mask <<= 1;
            }
            Debug.Write(sum + " - ");
        }
Juan Carlos Oropeza
  • 47,252
  • 12
  • 78
  • 118

2 Answers2

1

(i & mask) should only result in {0,1} and isn't

(i & mask) should return a result in {0,1} only when mask is 1 - that is, on the initial iteration. However, as soon as mask gets shifted by mask <<= 1 operation, the result of the next operation will be in {0,2}. As the mask gets shifted, possible results will become {0,4}, {0,8}, {0,16} and so on, because the only bit set to 1 in the mask would be moving to the left.

The reason why << operator doubles the number is the same as the reason why writing a zero after a decimal number has the effect of multiplying the number by ten: appending a zero to a number of any base is the same as multiplying that number by the value of base.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

Ok, I solve it creating an IF.

int[] elem = new int[] { 1, 2, 3 };
double maxElem = Math.Pow(2, elem.Length);

for (int i = 0; i < maxElem; first++)
{
    for (int run = 0; run < elem.Length; run++)
    {
        int mask = 1, sum = 0;
        if ((i & mask) > 0) // ADD THIS LINE
        {
            sum += elem[run];                    
        }
        mask <<= 1;
    }
}
Juan Carlos Oropeza
  • 47,252
  • 12
  • 78
  • 118