将前导“0x”的十六进制字符串转换为在 C++ 中签署空头?
我找到了使用 strtol
将十六进制字符串转换为 signed int
的代码,但我找不到短 int (2 个字节)的内容。这是我的代码:
while (!sCurrentFile.eof() )
{
getline (sCurrentFile,currentString);
sOutputFile<<strtol(currentString.c_str(),NULL,16)<<endl;
}
我的想法是读取一个具有 2 字节宽值(如 0xFFEE)的文件,将其转换为有符号 int 并将结果写入输出文件中。执行速度不是问题。
我可以找到一些方法来避免这个问题,但我想使用“一行”解决方案,所以也许你可以为此提供帮助:)
编辑:文件看起来像这样:
0x0400
0x03fe
0x03fe
...
编辑:我已经尝试过使用十六进制运算符,但在这样做之前我仍然必须将字符串转换为整数。
// This won't work as currentString is not an integer
myInt << std::hex << currentString.c_str();
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;
}
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 :)
Edit : The files look like 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();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这应该很简单:
当我们谈论文件时:
您不应该这样做:
这是因为当您阅读最后一行时,它不会设置 EOF。因此,当您循环并读取最后一行之后的行时, getline() 将失败,并且您将对 currentString 上次设置后的内容执行 STUFF 操作。因此实际上您将处理最后一行两次。
循环文件的正确方法是:
This should be simple:
While we are talking about files:
You should NOT do this:
This is because when you read the last line it does NOT set the EOF. So when you loop around and then read the line after the last line, getline() will fail and you will be doing STUFF on what was in currentString from the last time it was set up. So in-effect you will processes the last line twice.
The correct way to loop over a file is:
您可能可以使用 stringtream 类的 >>带有六角操纵器的操作员。
You can probably use stringtream class's >> operator with hex manipulator.
您是否考虑过使用带有“%hx”转换限定符的 sscanf?
Have you considered
sscanf
with the "%hx" conversion qualifier?如果您确定可以信任
currentString.c_str()
中的数据,那么您也可以轻松地执行以下操作If you're sure the data can be trusted from
currentString.c_str()
, then you could also easily do如果您知道数据始终采用这种格式,您难道不能这样做:
If you know the data is always going to be in that format, couldn't you just do something like: