字符串转换中的十六进制值
我有一个 C++ 脚本,其中涉及可能的十六进制数字的字符串表示形式。在脚本的后面部分中,我想将这些可能的十六进制数转换为双精度数,以进行以 10 为基数的算术。为了尝试进行此转换,我使用了一个函数。
double MyFunction(string input)
{
double Number;
stringstream ss(input);
ss >> hex >> Number;
return Number;
}
当我的脚本运行时,似乎转换后的字符串仅被视为十进制数。如果原始字符串是“fc”或“b5”,则表示转换后的数字为-9.25596e+061。但如果字符串是“33”(应该是 0x33),它会将其视为十进制 33。我已经尝试过不使用“>> 十六进制”并在转换之前在字符串中添加“0x”前缀(因为编译似乎理解 0xF 就像理解 16 一样),但没有这样的运气。
我知道计算机将所有内容存储为二进制,并且不存储查看数字的基数,但我根本不明白这里出了什么问题。为什么它似乎坚持以 10 为基数读取字符串并忽略任何 AF 实例?
任何帮助将不胜感激。
I have a C++ script which involves string representations of would-be hexadecimal numbers. In a later portion of the script, I would like to convert these would-be hexadecimal numbers into doubles for some arithmetic in base 10. To try to make this conversion, I use a function.
double MyFunction(string input)
{
double Number;
stringstream ss(input);
ss >> hex >> Number;
return Number;
}
When my script runs, it seems the resulting converted string is only considered as a decimal number. If the original string was "fc" or "b5", it says the converted number is -9.25596e+061. But if the string was "33" (which is supposed to be 0x33), it views it as decimal 33. I have tried it without the ">> hex" and with adding a "0x" prefix to the string before conversion (since the compile seems to understand 0xF just as it would 16), but no such luck.
I understand the computer stores everything as binary and that the base a number is viewed at is not stored, but I simply do not understand what is wrong here. Why does it seemingly insist upon reading the string in base 10 and disregarding any instance of A-F?
Any help will be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
十六进制操纵器仅适用于 int 等整数类型。首先将十六进制字符串输入整数,然后将其转换为双精度数:
The hex manipulator only works for integral types like int. First input the hexadecimal string into an integer and then convert that to a double: