如何将二进制值字符串转换回char

Geo*_*rge 9 c++ arrays string binary bitset

注意:我只关心信件.bitset 000001将是aA.

我有一个string名字s的值"abc".我把每char一个string并通过使用转换为二进制值bitset.

例如

bitset <6> b1 = s[0];   //a
bitset <6> b2 = s[1];   //b
bitset <6> b3 = s[2];   //c
Run Code Online (Sandbox Code Playgroud)

然后我希望把结果放到一个arraystrings.阵列的名称是arr(以及每个stringarray将代表每一个的二进制值char)

例如

arr[0]   //will hold the value of char 'a' in binary form which is 000001
arr[1]   //will hold the value of char 'b' in binary form which is 000010
arr[2]   //will hold the value of char 'c' in binary form which is 000011
Run Code Online (Sandbox Code Playgroud)

以及我将每个charstring二进制转换为二进制的方式

arr[0] = b1.to_string();    //arr[0] is now 000001
arr[1] = b2.to_string();    //arr[1] is now 000010
arr[2] = b3.to_string();    //arr[2] is now 000011
Run Code Online (Sandbox Code Playgroud)

现在这就是我的问题.我如何将它们转换回来char

例如

//I want each char to take back the each corresponding letter from the binary values

char c1;   //How do i make the arr[0] value of 000001 to become 'a' again?
char c2;   //Same here
char c3;   //And here
Run Code Online (Sandbox Code Playgroud)

vso*_*tco 5

假设您想要从ASCII代码64开始,而那'a'(或'A')只是000001在这种情况下,那么您可以这样做

c1 = static_cast<char>(std::bitset<6>(arr[0]).to_ulong() + 64); // 
Run Code Online (Sandbox Code Playgroud)

'A'十进制是65,二进制是0b01000001.'a'十进制是97,二进制是0b01100001.在您的代码中,您使用a bitset<6>来存储'a'(或'A').A bitset<6>只能代表2^6符号,即64你会遇到切割.基本上2最重要的位将被削减.在这种情况下,bitset<6>('A')变为0b000001,即1十进制,bitset<6>('a')变为0b1000001,即33十进制.您现在可以说服自己添加回来64会产生正确的结果.

编辑

请注意,您还可以使用std::stoi(仅限C++ 11)将位字符串从基数2转换为十进制,如其他答案中所述:

char c1 = static_cast<char>(std::stoi(arr[0], nullptr, 2) + 64);
Run Code Online (Sandbox Code Playgroud)