【问题标题】:Get decimal ascii value of a char获取char的十进制ascii值
【发布时间】:2017-04-05 11:32:37
【问题描述】:

我需要得到一个字符的十进制 ascii 值。到现在用这个打印(避免负值)没有问题。

char x;
cout << dec << (int)x << endl;

当我想将dec 值分配给int 变量时,问题就出现了,dec 不能在cout 之外使用。任何建议如何做到这一点?请注意,(int) char 不起作用,因为我也会得到负值,我想避免它们。

我已经尝试过使用atoiunsigned int,但到目前为止还没有成功。

【问题讨论】:

  • cout &lt;&lt; (int) x; 不是(int)char
  • 如果x&lt;0,则不是ASCII。
  • 为什么是&lt;&lt; dec?我不知道为什么,但我有一个大小为 1024 的chararray。如果我不输入&lt;&lt;dec,我会得到负值。我正在使用 VB2015
  • “十进制 ASCII 值”到底是什么意思? ASCII 码不是十进制、十六进制或二进制,它们是整数
  • @Capie 十进制和十六进制是不同的写下 相同数字的方法。

标签: c++ char type-conversion ascii


【解决方案1】:

char 类型的对象转换为unsigned char 类型的对象就足够了。例如

char c = CHAR_MIN; 

int x = ( unsigned char )c;

int x = static_cast<unsigned char>( c );

【讨论】:

    【解决方案2】:

    这取决于编译器的实现, 一些编译器将 char 实现为无符号,并允许扩展 ASCII 字符 (http://www.ascii-code.com/) ,下面两个链接的代码相同,只有一个有效 http://ideone.com/72Iiaz // 使用 gcc c++ 4.* 并且不编译 http://ideone.com/hbmBK6 // 使用 c++ 14

    #include<iostream>
    using namespace std;
    
    
    int main(){
        char ch = 'x';
        int num = ch;
        cout<<ch<<" => " << num << endl;
        ch = 'µ'; // should now have an extended ascii character
        num = ch;
        cout<<ch<<" => " << num << endl;
        cout<<" using unsigned "<< (unsigned int) 'µ';
        return 0;
    }
    

    【讨论】:

      【解决方案3】:

      在 C++ 中,使用 static_cast&lt;int&gt;( someCharValue )signed char(和 unsigned char)值转换为整数 - 但这不是有意义的操作,因为 char 无论如何都是整数类型。

      如果你想要一个十进制字符串,那么使用 C++11 的 std::to_string 函数:

      #include <string>
      
      using namespace std;
      
      char someChar = 'A';
      int someCharAsInteger = static_cast<int>( someChar ); // this step is unnecessary, but it's to demonstrate that they're all just integers.
      string someCharsNumericIntegerValueAsDecimalString1 = to_string( someChar ); // as there is no `to_string(char)` implicit upsizing to `int` will occur.
      string someCharsNumericIntegerValueAsDecimalString2 = to_string( someCharAsInteger );
      
      cout << someCharsNumericIntegerValueAsDecimalString1 << endl;
      cout << someCharsNumericIntegerValueAsDecimalString2 << endl;
      

      这将输出:

      65
      65
      

      ...假设您的系统是 ASCII。

      【讨论】:

      • 明天检查并通知您。
      【解决方案4】:

      您可以通过显式转换或隐式转换将字符转换为整数:

      int a = 'a'; // implicit conversion
      cout << a << endl; // 97
      
      int A = (int)'A'; explicit conversion
      cout << a << endl; // 65
      

      【讨论】:

        猜你喜欢
        • 2017-04-16
        • 1970-01-01
        • 1970-01-01
        • 2015-02-14
        • 2011-03-31
        • 2013-05-07
        • 2012-12-07
        • 2021-10-22
        • 2018-08-26
        相关资源
        最近更新 更多