Allanqunzi
Allanqunzi

Reputation: 3260

How to convert a string to a long or another string of ascii values?

In C++, how do you convert an ASCII string (with no more than 5 elements) to a string of the ASCII values, or a long like below?

str = "ABCDE"; --> ascii_value_str = "6566676869";

or

str = "ABCDE"; --> long_int = 6566676869;

Upvotes: 0

Views: 101

Answers (3)

surajs1n
surajs1n

Reputation: 1583

It would be easy to code if you are using c++11 because to_string() function is available for c++11 onwards. Now, all you have to do is play with their ASCII Values.

Look at code snippets :

1 Convert String into ASCII value string

#include <iostream>
#include <string>

using namespace std;

int main() {
    string str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ", output;

    for(int i=0; i<str.length(); i++) {
        output += to_string((int)str[i]);
    }

    cout<< output << endl;
    return 0;
}

2 Convert the String into ASCII value long int, but mind the range of long int. You might get wrong answer for the long input string, and now the code is.

#include <iostream>
#include <string>

using namespace std;

int main() {
    string str = "xyz";   
    long int output = 0;

    for(int i=0; i<str.length(); i++) {
        if(str[i]/100)  {       // three digit ASCII Value
            output = 1000*output + str[i];
        } else if(str[i]/10) {  // two digit ASCII Value
            output = 100*output + str[i];
        } else {                // one digit ASCII Value
            output = 10*output + str[i];
        }

    }

    cout<< output << endl;
    return 0;
}

Upvotes: 1

P0W
P0W

Reputation: 47794

Loop through the string "ABCDE" and convert each element to its ascii and add to the string ascii_value_str using std::to_string

for( const auto& ch: str )
{
  ascii_value_str  +=  std::to_string( (int) ch  );
}

For converting to your long_int, simply use std::atol

long int long_int = std::atol( ascii_value_str .c_str() );

Upvotes: 2

yizzlez
yizzlez

Reputation: 8805

You can just take each character and cast it to int:

int aval = (int) str[i];

Now you can turn it into a long through basic multiplication or use the to_string function to turn it into a string.

Upvotes: 1

Related Questions