如何反转位集中的位?

Roc*_*645 5 c++ bits bitset c++11

例如,我有整数

一 = 10;

它的二进制表示(对于 32 位整数)是

00000000000000000000000000001010

反过来,它变成

01010000000000000000000000000000

现在我已经看到了这段代码,来自这篇topcoder article可以完成这个

x = ((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1);
x = ((x & 0xcccccccc) >> 2) | ((x & 0x33333333) << 2);
x = ((x & 0xf0f0f0f0) >> 4) | ((x & 0x0f0f0f0f) << 4);
x = ((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8);
x = ((x & 0xffff0000) >> 16) | ((x & 0x0000ffff) << 16);
Run Code Online (Sandbox Code Playgroud)

现在有一些简单的方法可以达到相同的效果。也许通过将我们的位集转换为字符串,然后将其反转?将 bitset 转换为 bitset 字符串的构造函数和方法是如此复杂,我似乎无法弄清楚如何做到这一点。

这是我到目前为止尝试过的

#include <bitset>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <typeinfo>
#include <string>

using namespace std;

int main() {

    const unsigned int k = 32;


    int x = 10;
    bitset<k> nf(x);

    cout << nf << endl;

    string str =
        nf.to_string<char,string::traits_type,string::allocator_type>();

    reverse(str.begin(), str.end() + str.size());

    cout << str << endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但我得到这个作为输出:

00000000000000000000000000001010
G;ÿJG¥±žGsÿkìöUàä˜\éä˜\é
Run Code Online (Sandbox Code Playgroud)

Lin*_*gxi 8

更少的代码将使您在 TopCoder SRM 中赢得一些时间。以下是我将在 TopCoder SRM 中使用的内容(请在此处查看):

#include <algorithm>
#include <bitset>
#include <iostream>
#include <string>

int main() {
  auto x = std::bitset<32>(10);
  std::cout << x << std::endl;

  auto str = x.to_string();
  std::reverse(str.begin(), str.end());
  auto y = std::bitset<32>(str);
  std::cout << y << std::endl;

  return 0;
}
Run Code Online (Sandbox Code Playgroud)


Mat*_*lia 8

这是直接在位集上的微不足道的就地方法:

template<std::size_t N>
void reverse(std::bitset<N> &b) {
    for(std::size_t i = 0; i < N/2; ++i) {
        bool t = b[i];
        b[i] = b[N-i-1];
        b[N-i-1] = t;
    }
}
Run Code Online (Sandbox Code Playgroud)