5 Replies - 15733 Views - Last Post: 16 August 2011 - 08:41 PM Rate Topic: -----

#1 FljpFl0p  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 58
  • Joined: 13-October 10

Convert ASCII to String?

Posted 16 August 2011 - 10:20 AM

Hi there, I've been trying to convert String to binary and vice versa with this pattern: string->ascii->binary and binary->ascii->string. Most of the conversions are done except for ascii->string. I tried googling but all the results are either C or Java, none of which are C++. So would anyone be so kind to help me with this one? I'd appreciate it.
Here's my code, though they're all for the other conversions:
#include <iostream>
#include <string>
#include <cstdlib>
#include <sstream>
#include <math.h>

using namespace std;

int main()
{
	//Convert string to ASCII
	stringstream stream;
	string s1 = "A";
	cout << s1 << endl;	   
	int num;
	int total = 0;
	num = int(s1[0]);
	
	//Convert ASCII to binary
	while (num > 0)
	{
		total = num % 2;
		num /= 2;
		stream << total;
	}
	string binary = stream.str();
	cout << binary << endl;
	
	//Convert binary to ASCII
	int decimal = 0;
	
	for (int i = 0; i < binary.size(); i++)
	{
		if (binary[i] == '1')
			decimal += pow(2,binary.size() - i - 1);
	}
	
	cout << decimal;
	
	//Convert ASCII to string
	//...
	
	return 0;
}


Is This A Good Question/Topic? 0
  • +

Replies To: Convert ASCII to String?

#2 Hezekiah  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 207
  • View blog
  • Posts: 552
  • Joined: 12-July 09

Re: Convert ASCII to String?

Posted 16 August 2011 - 10:47 AM

You just have to convert the int back to a char. Something like:
string s2;
s2 = (char) decimal;
//you probably don't even need the (char)
s2 = decimal;

Note that string::operator= is overloaded to take a char.

Also, the C++ header is <cmath>, not <math.h>.
Was This Post Helpful? 1
  • +
  • -

#3 Bench  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 856
  • View blog
  • Posts: 2,339
  • Joined: 20-August 07

Re: Convert ASCII to String?

Posted 16 August 2011 - 10:48 AM

If you've got a free choice of how to solve this problem, then I recommend std::bitset which has got an automatic base-2 conversion built in to it. (Of course, if this is homework and you've been told that you must solve it in a particular way, then you may want to check with your tutor whether they want you to use bitset).

#include <iostream>
#include <string>
#include <sstream>
#include <cstdlib>      // CHAR_BIT (usually '#define CHAR_BIT 8' but YMMV)
#include <algorithm>    // std::copy
#include <iterator>     // std::ostream_iterator
#include <bitset>       // std::bitset<N>

int main()
{
    typedef std::bitset<CHAR_BIT> byte_type;
    std::ostringstream stream;
    std::string fred("hello");

    // Copy each char from fred into the stream, using base2 representation
    std::copy(fred.begin(),
              fred.end(),
              std::ostream_iterator<byte_type>(stream, " "));

    std::cout << stream.str() << std::endl;
}
Note: bitset can also accept a binary representation and convert that into a number aswell... e.g. std::bitset<8> bob("01010101");

This post has been edited by Bench: 16 August 2011 - 10:50 AM

Was This Post Helpful? 1
  • +
  • -

#4 FljpFl0p  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 58
  • Joined: 13-October 10

Re: Convert ASCII to String?

Posted 16 August 2011 - 10:53 AM

Doesn't seem to work for me...I was trying something else with the math.h header, forgot to replace it with cmath.

Oh wait, my bad, it works. I was being lazy and wrote "string s2 = (char) decimal"
@Bench: It's homework but it's not about all these conversions, they're just some utilities for the actual work. I tried bitset but doesn't really understand it so I just use a more "manual" way.

This post has been edited by FljpFl0p: 16 August 2011 - 10:57 AM

Was This Post Helpful? 0
  • +
  • -

#5 NickDMax  Icon User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2250
  • View blog
  • Posts: 9,245
  • Joined: 18-February 07

Re: Convert ASCII to String?

Posted 16 August 2011 - 12:35 PM

So you want to convert "ABC" into "010000010100001001000011"

which is: 0100 0001 | 0100 0010 | 0100 0011 = 0x41 0x42 0x43 = 'A' 'B' 'B'

#include <iostream>
#include <string>


using namespace std;

string tobin(unsigned char n) {
    string result = "";
    string one = "1";
    string zero = "0";
    for(int i = 0; i < 8*sizeof(unsigned char); ++i) {
        if (n & 1) {
            result = one + result;
        } else {
            result = zero + result;
        }
        n >>= 1; // shift bits down 1 place.
    }
    return result;
}

string tobin(string str) {
    string result = "";
    //string sp = " ";
    for(int i = 0; i < str.length(); ++i) {
        //result += sp + tobin(str[i]);
        result += tobin(str[i]);
    }
    return result;
}

int main() {

    cout << tobin("ABC") << endl;
    
    return 0;
}


no need for cmath. Next to convert back... So I have begun the process here, but my function only works with strings that are exactly 8 chars long (i.e. it will crash if the string is less than 8 chars long and will not convert more than 1 char).

#include <iostream>
#include <string>


using namespace std;

string tobin(unsigned char n) {
    string result = "";
    string one = "1";
    string zero = "0";
    for(int i = 0; i < 8*sizeof(unsigned char); ++i) {
        if (n & 1) {
            result = one + result;
        } else {
            result = zero + result;
        }
        n >>= 1; // shift bits down 1 place.
    }
    return result;
}

string tobin(string str) {
    string result = "";
    //string sp = " ";
    for(int i = 0; i < str.length(); ++i) {
        //result += sp + tobin(str[i]);
        result += tobin(str[i]);
    }
    return result;
}

unsigned char toASCII(string bits) {
    int result = 0;
    for(int i = 0; i < 8*sizeof(unsigned char); ++i) {
        result <<= 1;
        if (bits[i] == '1') {
            result |= 1;
            //cout << i << endl;
        }
    }
    return result;
}

int main() {
    //cout << tobin("ABC") << endl;
    string bits = tobin('A');
    cout <<  toASCII(bits) << endl;
    
    return 0;
}


You could use my function and find sub-strings, OR you could work out a more general way that would work with any length string and return a string rather than an unsigned char.
Was This Post Helpful? 0
  • +
  • -

#6 FljpFl0p  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 58
  • Joined: 13-October 10

Re: Convert ASCII to String?

Posted 16 August 2011 - 08:41 PM

Thanks man, but I need to read in a whole text file and this is just a minor part of the assignment so I'm not gonna go deep into it.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1