转换带有前导“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?
相关文章