简体   繁体   English

在C ++中将ASCII十进制转换为Char

[英]ASCII Dec to Char in C++

I want to get every characters of ASCII in normal char. 我想以普通字符获取ASCII的每个字符。 If I only put char key only, it would return dec. 如果我只输入char key ,它将返回dec。

My request: 我的请求:

char alph = //ascii dec to normal char

For example: A in dec is 65 Note: I don't have the characters, but I do have the ASCII codes in dec like 65. 例如:dec中的A是65注意:我没有字符,但确实有dec中的ASCII码,例如65。

because I need user input like 65 因为我需要像65这样的用户输入

In this case you can do this: 在这种情况下,您可以执行以下操作:

#include <iostream>

using namespace std;

int main() {
    int code;
    cout << "Enter a char code:" << endl;
    cin >> code;

    char char_from_code = code;
    cout << char_from_code << endl;

    return 0;
}

This will ouput: 这将输出:

Enter a char code:
65
A

It seems you have misunderstood the concept. 看来您误解了这个概念。

The numerical value is always there. 数值始终存在。 Whether you print it as the letter or the numerical value depends on how you print. 将其打印为字母还是数字取决于打印方式。

std::cout will print chars as letters (aka chars) so you'll need to cast it to another integer type to print the value. std :: cout会将字符打印为字母(又称字符),因此您需要将其转换为其他整数类型以打印值。

char c = 'a';
cout << c << endl;             // Prints a
cout << (uint32_t)c << endl;   // Prints 97

cout << endl;

uint32_t i=98;
cout << i << endl;
cout << (char)i << endl;

Output: 输出:

a
97

98
b

This is the method, very simple and then just need to make your own user interface to get input dec 这是方法,非常简单,然后只需创建自己的用户界面即可获得输入dec

#include <iostream>

using namespace std;

int main() {
    int dec = 65;
    cout << char(dec);
    cin.get();
    return 0;
}

Looks like you need hex/unhex converter. 看起来您需要十六进制/非十六进制转换器。 See at boost, or use this bicycle: 快来看看,或使用这辆自行车:

vector<unsigned char> dec2bin( const string& _hex )
{
    vector<unsigned char> ret;

    if( _hex.size() < 2 )
    {
        return ret;
    }

    for( size_t i = 0; i <= _hex.size() - 2; i += 2 )
    {
        string two = string( _hex.data() + i, 2 );
        stringstream ss( two );
        string ttt = ss.str();
        int tmp;
        ss >> /*hex >>*/ tmp;
        unsigned char c = (unsigned char)tmp;
        ret.insert( ret.end(), c );
     }

     return ret;
 }

 int main()
 {  
     string a = "65";
     unsigned char c = dec2bin( a )[0];
     cout << (char)c << endl;
     return 0;
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM