Convert hexadecimal string with leading quot;0xquot; to signed short in C++?(转换带有前导“0x的十六进制字符串在 C++ 中签名短?)
问题描述
我找到了使用 strtol
将十六进制字符串转换为 signed int
的代码,但我找不到短 int(2 个字节)的内容.这是我的一段代码:
I found the code to convert a hexadecimal string into a signed int
using strtol
, but I can't find something for a short int (2 bytes). Here' my piece of code :
while (!sCurrentFile.eof() )
{
getline (sCurrentFile,currentString);
sOutputFile<<strtol(currentString.c_str(),NULL,16)<<endl;
}
我的想法是读取具有 2 字节宽值的文件(如 0xFFEE),将其转换为有符号整数并将结果写入输出文件.执行速度不是问题.
My idea is to read a file with 2 bytes wide values (like 0xFFEE), convert it to signed int and write the result in an output file. Execution speed is not an issue.
我可以找到一些方法来避免这个问题,但我想使用单线"解决方案,所以也许你可以为此提供帮助:)
I could find some ways to avoid the problem, but I'd like to use a "one line" solution, so maybe you can help for this :)
文件如下所示:
0x0400
0x03fe
0x03fe
...
我已经尝试过使用十六进制运算符,但在这样做之前我仍然需要将字符串转换为整数.
Edit : I already tried with the hex operator, but I still have to convert the string to an integer before doing so.
// This won't work as currentString is not an integer
myInt << std::hex << currentString.c_str();
推荐答案
您是否考虑过带有%hx"转换限定符的 sscanf
?
Have you considered sscanf
with the "%hx" conversion qualifier?
这篇关于转换带有前导“0x"的十六进制字符串在 C++ 中签名短?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:转换带有前导“0x"的十六进制字符串在 C++ 中签名短?


- 静态初始化顺序失败 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- C++ 协变模板 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 从python回调到c++的选项 2022-11-16
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 近似搜索的工作原理 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01