Convert char or string to bits in C ++

I perform the assignment when DES is encrypted, and I cannot convert the string, not to mention char, to bits. Can someone show me how to convert one char to bits in C ++?

+4
source share
1 answer

Following:

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

must work.

See http://ideone.com/PtSFvz


Converting an arbitrary length stringto is bitsetmore difficult, if at all possible. The size of the bit set must be known at compile time, so there really is no way to convert a string to one.

However, if you know the length of the string at compile time (or you can bind 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;
  }
}

, , .

+5

Source: https://habr.com/ru/post/1537010/


All Articles