Convert char or string to bitset in c++

ShienXIII picture ShienXIII · Apr 17, 2014 · Viewed 12.4k times · Source

I'm doing an assignment on DES encryption and I can't seem to convert a string, let alone a char into a bitset. Can anyone show me how to convert a single char into a bitset in C++?

Answer

Alec picture Alec · Apr 17, 2014

The following:

char c = 'A';
std::bitset<8> b(c);  // implicit cast to unsigned long long

should work.

See http://ideone.com/PtSFvz


Converting an arbitrary-length string to a bitset is harder, if at all possible. The size of a bitset must be known at compile-time, so there's not really a way of converting a string to one.

However, if you know the length of your string at compile-time (or can bound it at compile time), you can do something like:

const size_t N = 50;  // bound on string length
bitset<N * 8> b;
for (int i = 0; i < str.length(); ++i) {
  char c = s[i];
  for (int j = 7; j >= 0 && c; --j) {
    if (c & 0x1) {
      b.set(8 * i + j);
    }
    c >>= 1;
  }
}

That may be a bit inefficient but I don't know if there's a better work-around.