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

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

本文介绍了如何将二进制值的字符串转换回char的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例

注意:我只关心字母.因此位集000001将为aA.

NOTE: that i am only concerned about letters. so bitset 000001 would be a or A.

我有一个名为sstring,其值为"abc".我将string中的每个char都通过以下方式转换为二进制值bitset的使用.

I have a string named s with the value "abc".I take each char of the string and convert it to binary value throughthe use of bitset.

例如

bitset <6> b1 = s[0];   //a
bitset <6> b2 = s[1];   //b
bitset <6> b3 = s[2];   //c

然后我要将结果放入stringsarray中.数组的名称为arr(array的每个string将代表每个char的二进制值)

then i want to put the results into an array of strings. The name of the array is arr (and each string of the array will represent the binary value of each 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

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

and the way i convert each char from the string to binary is

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

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

Now here lies my problem.How do i convert them back to 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

推荐答案

假定您要从ASCII代码64开始,并且在这种情况下'a'(或'A')就是000001,那么您可以简单地做

Assuming you want to start at ASCII code 64, and that 'a' (or 'A') is simply 000001 in that case, then you can simply do

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

十进制

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

'A' in decimal is 65, in binary is 0b01000001. 'a' in decimal is 97, in binary is 0b01100001. In your code, you use a bitset<6> to store 'a' (or 'A'). A bitset<6> can only represent 2^6 symbols, i.e. 64, so you will encounter cutting. Basically the 2 most significant bits will be cut. In this case, bitset<6>('A') becomes 0b000001, i.e. 1 in decimal, and bitset<6>('a') becomes 0b1000001, i.e. 33 in decimal. You can now convince yourself that adding back 64 produces the right result.

编辑

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

Note that you can also use std::stoi (C++11 only) to convert the bit string from base 2 to decimal, as mentioned in the other answers:

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

这篇关于如何将二进制值的字符串转换回char的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 09:48