0

I found this bit of code (no pun intended) that solves a problem I needed to solve but I don't really understand what the (i & (1 << j)) part does. Is there a more "high level" way of writing it so I can understand it? Or a different way of doing the same thing that is less "pure"?


//this is not the actual code, just bits of it so you have an idea of how the variables are used

for (i = 0; i < vectorsize; i++) {
void findsubsets(unsigned int *value, int n, int i)
}

void findsubsets {
     for (j = 0; j < n; j++) {
        if (i & (1 << j)) {
            //print something
        }
    }
}

I would like an alternative to that statement, that does the same thing (or rather, solves the same problem) but is more "usual". I am of course only referring to the bitwise shift.

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
Martin
  • 47
  • 1
  • 6
  • 5
    `i & (1 << j)` is actually quite readable IMO. Why do you think it is "unusual"? – L. F. Sep 13 '19 at 01:02
  • It's a bit test. `i` is the value, `j` is the bit to test. – Michael Dorgan Sep 13 '19 at 01:09
  • computers use binary and if you want to control them (efficiently) you need to know how to work with the binary digits, A.K.A bits using bitwise operators. [What are bitwise shift (bit-shift) operators and how do they work?](https://stackoverflow.com/q/141525/995714), [What are bitwise operators?](https://stackoverflow.com/q/276706/995714) – phuclv Sep 13 '19 at 01:47
  • I'm kind of a newbie, so I haven't seen it yet. But good to know it's not unusual. – Martin Sep 13 '19 at 02:43
  • Better to use `unsigned i` than `int i` and use `1u` than `1`. – chux - Reinstate Monica Sep 13 '19 at 02:46
  • Thanks! And why exactly is this expression important? What does it condition? I'm not sure I quite understand what it does yet. Be patient with me, I'm just getting started with coding :) – Martin Sep 13 '19 at 03:00

2 Answers2

3

That is very "usual". It tests if the jth bit of i is set. Another way is if ((i >> j) & 1).

If you want it to be self documenting, write a nicely named helper function:

bool jth_bit(int i, int j) { return (i >> j) & 1; }

(Depending on which edition of C you use, you may want _Bool instead of bool)

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
0

As Mr. Voigt has pointed out the expression i & (1 << j) simply checks if the j-th bit is set in the i variable. This is a pretty standard way of doing things in C.

To improve readability you can do this:

// Return value with n-th bit set to 1
int bit(int n) { return 1 << n; }

...

for (j = 0; j < n; j++)
{
    if (i & bit(j))
    {
        //print something
    }
}

Another way is to "hide" the expression inside a function with a meaningful name:

bool is_bit_set_in(int var, int n) { return var & (1 << n); }

...

for (j = 0; j < n; j++)
{
    if (is_bit_set_in(i, j))
    {
        //print something
    }
}