Convert char or string to bitset in c++

岁酱吖の 提交于 2019-12-06 04:28:15

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/23142363/convert-char-or-string-to-bitset-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!