简体   繁体   English

你能给我解释一下这段按位运算符的代码吗? [复制]

[英]Can you explain this code of bitwise operator to me? [duplicate]

void printPowerSet(char *set, int set_size) {

  unsigned int pow_set_size = pow(2, set_size);
  int counter, j;

  for (counter = 0; counter < pow_set_size; counter++) {
    for (j = 0; j < set_size; j++) {

      if (counter & (1 << j))
        cout << set[j];
    }
    cout << endl;
  }
}

I am not able to understand the if (counter & (1 << j)) part here.我无法理解这里的if (counter & (1 << j))部分。 How can this code give subsets of a set {a,b,c} ?这段代码如何给出集合set {a,b,c}子集?

The main loop is iterating from 0 to (2^set_size)-1.主循环从 0 迭代到 (2^set_size)-1。 For example if there are three elements in the set it will iterate from 0 to 7 ((2^3)-1).例如,如果集合中有三个元素,它将从 0 迭代到 7 ((2^3)-1)。 If you represent it in binary it will be: 000, 001, 010, 011, 100, 101, 110, 111. These are all subsets of a three-element set (1 - we take the element, 0 - we don't take it).如果用二进制表示,它将是:000、001、010、011、100、101、110、111。这些都是三元素集的子集(1 - 我们取元素,0 - 我们不取元素拿着)。 Now you only need to iterate and check if we take j-th element (if the j-th bit is equal to 1).现在你只需要迭代并检查我们是否取第 j 个元素(如果第 j 位等于 1)。 The easiest way to do it is to check if (i & (2^j)) is equal to a non-zero value (& is a bitwise operation that for every position in the numbers returns 1 if in both numbers have on this position a lit bit and 0 in any other case).最简单的方法是检查 (i & (2^j)) 是否等于非零值(& 是一个按位运算,对于数字中的每个 position,如果两个数字都在这个 position 上,则返回 1一点亮,其他情况下为 0)。 The if operation treats 0 as false and positive values as true, so if the j-th bit is lit the operation will return 2^j and it will be a true value, so this element will be taken to this subset, otherwise if the bit isn't lit the operation will return 0, so this element isn't in this subset. if 操作将 0 视为 false 并将正值视为 true,因此如果第 j 位点亮,则该操作将返回 2^j 并且它将是一个 true 值,因此该元素将被带入该子集,否则如果位未点亮操作将返回 0,因此该元素不在该子集中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM