用前导“0x”转换十六进制字符串在C ++中签名简短? [英] Convert hexadecimal string with leading "0x" to signed short in C++?

查看:244
本文介绍了用前导“0x”转换十六进制字符串在C ++中签名简短?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了使用 strtol 将十六进制字符串转换为 signed int 的代码,但是我无法找到一个简短的int(2个字节)。这里是我的一段代码:

  while(!sCurrentFile.eof())
{
getline (sCurrentFile,currentString);
sOutputFile<< strtol(currentString.c_str(),NULL,16)<< endl;
}

我的想法是读取一个2字节宽的文件(如0xFFEE) ,将其转换为signed int并将结果写入输出文件。执行速度并不是问题。



我可以找到一些方法来避免这个问题,但我想使用单行解决方案,所以也许你可以)
$ b

编辑:这些文件看起来像这样:

  0x0400 
0x03fe
0x03fe
...

编辑:我已经尝试过使用十六进制运算符,但在这样做之前,我仍然必须将字符串转换为整数。

  //这将不起作用,因为currentString不是整数
myInt<< std :: hex<< currentString.c_str();


解决方案

您是否考虑过 sscanf 与%hx转换限定符?


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(); 

解决方案

Have you considered sscanf with the "%hx" conversion qualifier?

这篇关于用前导“0x”转换十六进制字符串在C ++中签名简短?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆