c ++将字符串转换为十六进制

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11608878/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 15:20:22  来源:igfitidea点击:

c++ convert string to hex

c++stringhex

提问by Homer

Possible Duplicate:
C++ convert hex string to signed integer

可能的重复:
C++ 将十六进制字符串转换为有符号整数

I allready searched on google but didn't find any help. So heres my problem: I have strings that allready contains hex code e.g.: string s1 = "5f0066" and i want to convert this string to hex. I need to compare the string with hex code i've read in a binary file.

我已经在谷歌上搜索过,但没有找到任何帮助。所以这是我的问题:我的字符串已经包含十六进制代码,例如:string s1 = "5f0066",我想将此字符串转换为十六进制。我需要将字符串与我在二进制文件中读取的十六进制代码进行比较。

(Just need the basic idea how to convert the string) 5f Best regards and thanks.

(只需要了解如何转换字符串的基本思路) 5f 最好的问候和感谢。

Edit: Got the binary file info in the format of unsigned char. SO its 0x5f... WOuld like to have teh string in the same format

编辑:以无符号字符格式获取二进制文件信息。所以它的 0x5f ......希望有相同格式的字符串

回答by Nawaz

Use std:stoias (in C++11 only):

使用std:stoi如(在C ++ 11只):

std::string s = "5f0066";
int num = std::stoi(s, 0, 16);

Online demo

在线演示

回答by Yochai Timmer

Use stringstreamand std::hex

使用stringstreamstd::hex

std::stringstream str;
std::string s1 = "5f0066";
str << s1;
int value;
str >> std::hex >> value;

回答by CygnusX1

strtol(str, NULL, 16)or strtoul(str, NULL, 16)should do what you need.

strtol(str, NULL, 16)或者strtoul(str, NULL, 16)应该做你需要的。

strtolstrtoul

斯特托尔斯特托尔