首页 > 代码库 > C++关于二进制位操作小结

C++关于二进制位操作小结

#include <iostream>
using namespace std;
//二进制位逆序。
int Grial(int x)
{
    int n = 32;
    int count = 0;
    while (n--)
    {
        count|= ((x&0x1) << n);
        x = ((unsigned)x >> 1);
    }
    return count;
}
int main()
{
    cout << Grial(1) << endl;
    return 0;
}


#include <iostream>
using namespace std;
//二进制位中的奇偶位互换。
int Grial(int x)
{
    int sum1 = x & 0x55555555;
    int sum2 = x & 0xaaaaaaaa;
    sum1 <<= 1;
    sum2 >>= 1;
    return sum1 | sum2;
}
int main()
{
    cout << Grial(6) << endl;
    return 0;
}


#include <iostream>
using namespace std;
//求两个数的和。

int Grial(int x, int y) { if (!y)return x; //int ret = x^y; //-1%2=-1; int sum = x^y; int num = ((x&y)<<1); return Grial(sum,num); } int main() { cout << Grial(3, 5) << endl; return 0; } #include <iostream> using namespace std; //推断一个数是不是2的n次方。 bool Grial(int x) { return (x&(x - 1)) == 0; } int main() { cout << Grial(4) << endl; return 0; } #include <iostream> using namespace std; //求二进制中1的个数。 int Grial(int x) { int count = 0; while (x) { x = x&(x - 1); count++; } return count; } int main() { cout << Grial(15) << endl; } #include <iostream> using namespace std; //求平均值。 int Grial(int x,int y) { return (x&y) + ((x^y) >> 1); } int main() { cout << Grial(20, 48) << endl; return 0; } #include <iostream> using namespace std; //求平均值。 int Grial(int x,int y) { return x - (x - y) / 2; } int main() { cout << Grial(3,9) << endl; return 0; }

<script type="text/javascript"> $(function () { $(‘pre.prettyprint code‘).each(function () { var lines = $(this).text().split(‘\n‘).length; var $numbering = $(‘
    ‘).addClass(‘pre-numbering‘).hide(); $(this).addClass(‘has-numbering‘).parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($(‘
  • ‘).text(i)); }; $numbering.fadeIn(1700); }); }); </script>

C++关于二进制位操作小结