“&-” 在 C++ 中表示按位与和按位取反操作。

huangapple go评论160阅读模式
英文:

what is "&-" mean in c++

问题

I have never seen this symbol before in c++, how does it work?

这是C++中的代码片段,下面是其翻译:

#include <iostream>
#include <vector>
using namespace std;
void print(int i){
    vector<int> a;
    while (i){
        a.push_back(i%2);
        i/=2;
    }
    for (int i=a.size()-1; i>=0; i--)
        cout<<a[i];
}
int main() {
    
    for (int i=1000; i>0; i-=(i&-i)){
        cout<<i<<' '<<int(i&i)<<' '<<int(i&-i)<<' ';
        print(i); cout<<' '; print(int(i&-i));
        cout<<'\n';
    }
    cout<<'\n';
    for (int i=5; i<=1000; i+=(i&-i)){
        cout<<i<<' '<<int(i&-i)<<' ';
        print(i); cout<<' '; print(int(i&-i));
        cout<<'\n';
    }
    return 0;
}

它的运行结果如下:

  • 1000 1000 8 1111101000 1000
  • 992 992 32 1111100000 100000
  • 960 960 64 1111000000 1000000
  • 896 896 128 1110000000 10000000
  • 768 768 256 1100000000 100000000
  • 512 512 512 1000000000 1000000000
  • 5 1 101 1
  • 6 2 110 10
  • 8 8 1000 1000
  • 16 16 10000 10000
  • 32 32 100000 100000
  • 64 64 1000000 1000000
  • 128 128 10000000 10000000
  • 256 256 100000000 100000000
  • 512 512 1000000000 1000000000
英文:

I have never seen this symbol before in c++, how does it work?

#include &lt;iostream&gt;
#include &lt;vector&gt;
using namespace std;
void print(int i){
    vector &lt;int&gt; a;
    while (i){
        a.push_back(i%2);
        i/=2;
    }
    for (int i=a.size()-1; i&gt;=0; i--)
        cout&lt;&lt;a[i];
}
int main() {
    
    for (int i=1000; i&gt;0; i-=(i&amp;-i)){
        cout&lt;&lt;i&lt;&lt;&#39; &#39;&lt;&lt;int(i&amp;i)&lt;&lt;&#39; &#39;&lt;&lt;int(i&amp;-i)&lt;&lt;&#39; &#39;;
        print(i); cout&lt;&lt;&#39; &#39;; print(int(i&amp;-i));
        cout&lt;&lt;&#39;\n&#39;;
    }
    cout&lt;&lt;&#39;\n&#39;;
    for (int i=5; i&lt;=1000; i+=(i&amp;-i)){
        cout&lt;&lt;i&lt;&lt;&#39; &#39;&lt;&lt;int(i&amp;-i)&lt;&lt;&#39; &#39;;
        print(i); cout&lt;&lt;&#39; &#39;; print(int(i&amp;-i));
        cout&lt;&lt;&#39;\n&#39;;
    }
    return 0;

and it result

  • 1000 1000 8 1111101000 1000
  • 992 992 32 1111100000 100000
  • 960 960 64 1111000000 1000000
  • 896 896 128 1110000000 10000000
  • 768 768 256 1100000000 100000000
  • 512 512 512 1000000000 1000000000
  • 5 1 101 1
  • 6 2 110 10
  • 8 8 1000 1000
  • 16 16 10000 10000
  • 32 32 100000 100000
  • 64 64 1000000 1000000
  • 128 128 10000000 10000000
  • 256 256 100000000 100000000
  • 512 512 1000000000 1000000000

答案1

得分: 3

这个表达应该被理解为 i & (-i)。这是一种获取整数 i 中最低有效位的值的"技巧"。

英文:

The expression should be read as i &amp; (-i). This is a "hack" to get the value of the least significant set bit in i.

huangapple
  • 本文由 发表于 2023年2月26日 21:42:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75572390.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定