提问人:ollydbg23 提问时间:5/24/2023 最后编辑:DailyLearnerollydbg23 更新时间:5/24/2023 访问量:104
std::hex 输入格式是否可以支持带有 2 补码表示法的否定int16_t十六进制字符串,例如“-1”的“ffff”?
Can std::hex input format support negtive int16_t hex string with two's complement notation such as `ffff` for `-1`?
问:
我想输入一个文本字符串给 ,值应该是 。ffff
int16_t
-1
下面是一个简单的测试C++程序:
#include <iostream>
#include <iomanip>
#include <stdint.h>
int main() {
int16_t num;
std::cout << "Enter a hexadecimal number: ";
std::cin >> std::hex >> num;
std::cout << "Decimal representation: " << num << std::endl;
return 0;
}
以下是该计划的结果:
Enter a hexadecimal number: ffff
Decimal representation: 32767
你看,结果值是 的最大值。32767
int16_t
所以,我的猜测是该行不支持十六进制格式的 Two 补码符号?std::cin >> std::hex >> num;
答:
0赞
Caleb.Steinmetz
5/24/2023
#1
此外,为了解决这个问题,您可以将 num 变成uint16_t,然后在使用它时将 num 转换为int16_t。
uint16_t num;
std::cin >> std::hex >> num;
std::cout << (int16_t)num;
return 0;
评论
0赞
ollydbg23
5/24/2023
是的,这有效。事实上,我有一个变量要填写。我认为你的答案可以通过 paddy 的评论来改进。你能把它添加到你的答案中吗?谢谢。int16_t
评论
long
int16_t
std::cin >> std::hex >> reinterpret_cast<uint16_t&>(num);
Extracts a short value potentially skipping preceding whitespace.
>>
ffff
65535