4

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++?

ShienXIII
  • 141
  • 1
  • 1
  • 9
  • 3
    [`std::bitset`](http://en.cppreference.com/w/cpp/utility/bitset) accepts a string for construction. Have you considered using it? – Captain Obvlious Apr 17 '14 at 20:07

1 Answers1

7

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.

alecbz
  • 6,292
  • 4
  • 30
  • 50