将ASCII字符串转换为十进制和十六进制表示形式 [英] Convert ASCII string into Decimal and Hexadecimal Representations

查看:528
本文介绍了将ASCII字符串转换为十进制和十六进制表示形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将ASCII字符串(如...hello2)转换为十进制和/或十六进制表示形式(数字形式,具体类型是不相关的)。所以,你好将是:68 65 6c 6c 6f 32在HEX。

I need to convert an ASCII string like... "hello2" into it's decimal and or hexadecimal representation (a numeric form, the specific kind is irrelevant). So, "hello" would be : 68 65 6c 6c 6f 32 in HEX. How do I do this in C++ without just using a giant if statement?

编辑:好的,这是我用的解决方案:

Okay so this is the solution I went with:

int main()
{
    string c = "B";
    char *cs = new char[c.size() + 1];
    std::strcpy ( cs, c.c_str() );
    cout << cs << endl;

    char a = *cs;
    int as = a;
    cout << as << endl;
    return 0;
}


推荐答案

将结果写入stdout,或者可以使用sprintf / snprintf将结果写入字符串。这里的关键是格式字符串中的%X。

You can use printf() to write the result to stdout or you could use sprintf / snprintf to write the result to a string. The key here is the %X in the format string.

#include <cstdio>
#include <cstring>
int main(int argc, char **argv)
{
    char *string = "hello2";
    int i;

    for (i = 0; i < strlen(string); i++)
        printf("%X", string[i]);

    return 0;
}

如果处理C ++ std :: string,可以使用字符串的c_str ()方法产生一个C字符数组。

If dealing with a C++ std::string, you could use the string's c_str() method to yield a C character array.

这篇关于将ASCII字符串转换为十进制和十六进制表示形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆