How to convert string of binary values back to char

George picture George · Jun 2, 2015 · Viewed 9k times · Source

Example

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

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

e.g

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

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)

e.g

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

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

Now here lies my problem. How do i convert them back to char?

e.g.

//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

Answer

vsoftco picture vsoftco · Jun 2, 2015

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' 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.

EDIT

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);