简体   繁体   English

将一串十六进制存储到char中?

[英]Store a string of hex into a char?

so I have a string that has a hex value in it. 所以我有一个十六进制值的字符串。 For example, my string may have 例如,我的字符串可能有

string a = "0x4D";

Would it be possible to assign 0x4D to a char ? 是否可以将0x4D分配给char Because I know that if I had 因为我知道如果我有

char c = 0x4D then I could print out its ASCII symbol, which would be M . char c = 0x4D然后我可以打印出它的ASCII符号,即M。

Is it possible to store "0x4D" into a char so that I can print out its ascii symbol? 是否可以将“0x4D”存储到char中,以便打印出其ascii符号? If anyone has any tips, that would be appreciated! 如果有人有任何提示,那将不胜感激! If there's a better way to do this, please let me know! 如果有更好的方法,请告诉我! Thanks! 谢谢!

You can use strtol to convert the string to a number. 您可以使用strtol将字符串转换为数字。 You can then print this number or do other things you like with it. 然后,您可以打印此号码或使用它做其他您喜欢的事情。

Oh wait, you tagged it C++, and strtol is very much C-style. 哦等等,你把它标记为C ++,而strtol非常C风格。 In C++, you can use a stringstream, and extract a number from it. 在C ++中,您可以使用字符串流,并从中提取数字。

You can use std::stoi to convert the string to an integer (the base is auto-detected from the 0x prefix): 您可以使用std::stoi将字符串转换为整数(从0x前缀自动检测到基数):

std::string str = "0x4D";
char c = static_cast<char>(std::stoi(str));
std::cout << c << std::endl;

However, this is not guaranteed to give you the ASCII character for that value. 但是,不能保证为您提供该值的ASCII字符。 There are various translations between character sets that occur in this simple code alone. 单独使用此简单代码时,字符集之间存在各种转换。 For example, the char s in the string literal "0x4D" are initialized with the corresponding value in the implementation-defined execution character set . 例如,字符串文字"0x4D"中的char用实现定义的执行字符集中的相应值初始化。 The printed character is also up to interpretation by the medium that is displaying it. 打印的字符也可由显示它的介质解释。

The best you could do is provide a mapping from ASCII values to characters. 您可以做的最好的事情是提供从ASCII值到字符的映射。 You could do this with an array where the index is the ASCII value and the element is the corresponding character. 您可以使用数组执行此操作,其中索引是ASCII值,元素是相应的字符。

To use stringstreams as Bas suggests: 使用字符串流作为Bas建议:

int x;
string s = "0x10";
stringstream ss;
ss << hex << s;
ss >> x;

But I think it's a wasteful way to do it. 但我认为这样做是浪费的方式。

Here is a solution based on std::stringstream : 这是一个基于std::stringstream的解决方案:

std::istringstream iss ("0x4D");
iss.flags(std::ios::hex);
int i;
iss >> i;

std::cout << "[" << (char)i << "]" << std::endl;   //--> prints "[M]"

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

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