【问题标题】:Converting from ASCII back to char从 ASCII 转换回 char
【发布时间】:2013-11-20 20:35:33
【问题描述】:

我有一个已经将字符串转换为 ASCII 整数的函数,但是我该如何做相反的事情呢?谢谢

【问题讨论】:

  • 什么是“ASCII int”?您是指某种数组或某种向量中的文字 int 吗?根据定义,ASCII 只需要unsigned char 来存储它,它是纯粹的 8 位表示。
  • 什么是“反面”?输入的格式是什么?似乎是一个微不足道的问题。
  • 请编辑您的问题以提供转换示例。

标签: c++ string char ascii


【解决方案1】:

以下是一些使用std::bitset在数字和二进制格式数字的文本表示之间进行转换的示例(仅适用于可以用 7 位表示的字符集(例如 US-ASCII)):

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

【讨论】:

  • 这里没有任何东西依赖于 ASCII。不过,它确实假设字符可以用 7 位表示。
  • @PeteBecker 这就是为什么它不能用于例如将包含某个字符的 bitset 使用超过 7 位从某个扩展集中转换为 char。不过,使用 7 位的标准 ASCII 字符集应该没问题。
  • 重点是ASCII不是唯一可以用7位表示的字符集。
【解决方案2】:

你的问题不清楚。基于您的 ASCII 整数(以您的术语)存储在 vector&lt;int&gt; 中的假设为您提供解决方案

下面的函数会将其转换为字符串:

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

【讨论】:

    【解决方案3】:

    这是一个更简单的方法!

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

    【讨论】:

      【解决方案4】:

      新词“ASCII 'int'”的使用是对 ASCII 代码的不精确——但不是不清楚——引用。参考很清楚,因为所有的 ASCII 代码都是整数,就像整数一样。

      最初的发布者能够将 ASCII 字符转换为十进制,大概是使用函数。

      在 MySQL 中,这将是:SELECT ASCII('A') [FROM DUAL];,返回 65。

      要反转方向,请使用 char() 函数: 选择字符(65)[从双];

      也许这对您来说是一个很好的解决方法。

      我建议使用非 GUI 客户端。

      【讨论】:

      • 我不完全确定为特定于 C++ 的问题提供特定于 MySQL(甚至是 SQL)的答案是否有意义。
      【解决方案5】:

      static 转换为cast 的最佳方法是

      int it=5;
      char W = static_cast<char>(*it);
      

      【讨论】:

        【解决方案6】:

        您只需将其存储在 char 变量中:

        //Let's say your original char was 'A'...
        int asciivalue = int('A');
        
        // Now asciivalue = 65
        
        //to convert it back:
        char orig = asciivalue;
        
        cout << orig << endl;
        

        它会输出'A'。

        【讨论】:

          猜你喜欢
          • 2014-10-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-05-15
          • 1970-01-01
          相关资源
          最近更新 更多