C++ - binary to string

Jul 10, 2011 at 7:20pm
Ok, I last posted about my string to binary conversion and got your help. But now I need help getting the binary back into ASCII characters. I got it to print it, but it still prints the binary numbers after it. I don't know where in this code it does that because I didn't write this one.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

string BinaryConverter::Decode(string _input){
	int length = _input.length();     //get length of string
	stringstream ss(_input);
	int binary[8];		   //array used to store 1 byte of binary number (1 character)
	int asciiNum = 0;      //the ascii number after conversion from binary
	char ascii;			   //the ascii character itself
	int z = 0;   //counter used
	for(int x = 0; x < length / 8; x++)				//reading in bytes. total characters = length / 8
	{
		for(int a = 0; a < 8; a++)					//store info into binary[0] through binary[7]
		{
			binary[a] = (int) _input[z] - 48;       //z never resets
			z++;
		}
		int power[8];			//will set powers of 2 in an array
		int counter = 7;        //power starts at 2^0, ends at 2^7
		for(int x = 0; x < 8; x++)
		{
			power[x] = counter;      //power[] = {7, 6, 5, ..... 1, 0}
			counter--;				 //decrement counter each time
		}
		for(int y = 0; y < 8; y++)    //will compute asciiNum
		{
			double a = binary[y];     //store the element from binary[] as "a"
			double b = power[y];      //store the lement from power[] as "b"
			asciiNum += a* pow(2, b);   //asciiNum = sum of a * 2^power where 0 <= power <= 7, power is int
		}
		ss.clear();
		ascii = asciiNum;   //assign the asciiNum value to ascii, to change it into an actual character
		asciiNum = 0;       //reset asciiNum for next loop
		ss << ascii;	    //display the ascii character
	}
	return ss.str();
}


And that would when called in my main function:
1
2
BinaryConverter bc;
cout << bc.Decode("0110100001100101011011000110110001101111");


And that would return:

hello0110100001100101011011000110110001101111


I want to remove the trailing binary code.
Jul 10, 2011 at 8:09pm
Line 3 must be:
stringstream ss;
Topic archived. No new replies allowed.