当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - Converting from ASCII back to char

问题描述:

I have a function that already converts a string to ASCII ints, but how to I do the reverse? Thanks

网友答案:

You question is not clear. Giving you solution based on assumption that your ASCII ints (in your terms) stored in a vector<int>

Below function will convert it into string:

std::string
AsciiIntToString ( std::vector<int> const& ascii_ints ) 
{
    std:: string ret_val;
    std::vector<int>:: const_iterator it = ascii_ints. begin ();
    for ( ; it != ascii_ints. end (); ++it ) {
        if ( *it < 0 || *it > 255) throw std::exception ("Invalid ASCII code");
        ret_val += static_cast<char>(*it);
    }
    return ret_val;
}
网友答案:

Here are some examples that convert between number and the textual representation of the number in binary format using std::bitset (only works for character sets that can be represented by 7 bits (as US-ASCII for example)):

char c = 'a';

// char to int.
int i = static_cast<int>(c);
// int to string (works for char to string also).
std::string bits = std::bitset<8>(i).to_string();

// string to (unsigned long) int.
unsigned long ul = std::bitset<8>(bits).to_ulong();
// int to char.
c = static_cast<char>(ul);
网友答案:

Here is a much simpler way!

void convertToString()
{
    char redo;
    int letter;
    int length;

    do{
        cout<< "How long is your word \n";
        cin >> length;
        cout << "Type in the letter values \n";

        for (int x = 0; x < length; x++)
        {
            cin >> letter;
            cout << char (letter);
        }

        cout << "\n To enter another word hit R" << endl;
        cin >> redo;
    } while (redo == 'R');    
}
网友答案:

The use of the neologism "ASCII 'int'" was an imprecise--but not an unclear--reference to ASCII codes. The reference was clear because all of the ASCII codes are whole numbers, just like integers.

The original poster was able to translate an ASCII character into decimal, presumably using a function.

In MySQL, this would be: SELECT ASCII('A') [FROM DUAL];, which returns 65.

To reverse direction, use the char() function: SELECT CHAR(65) [FROM DUAL];

Perhaps this would be a good work-around for you.

I would recommend using non-GUI client.

分享给朋友:
您可能感兴趣的文章:
随机阅读: