简体   繁体   English

读入十六进制值会在C ++中给出错误的数字

[英]Reading in hex value gives the wrong number in C++

I am trying to read in a hex value using the following code. 我正在尝试使用以下代码读取十六进制值。 It is supposed to read in a value from dataFile and the value is supposed to be "810c0001". 应该从dataFile中读取一个值,并且该值应该是“ 810c0001”。

int in;
dataFile>>hex>>in>>dec;
cout <<"I just wrote the value: "<<hex<<in<<dec<<endl;

After I run the program the output is shown as "I just wrote the value: 7fffffff". 运行程序后,输出显示为“我刚刚写了值:7fffffff”。 I noticed this problem only occurs when the most significant bit is filled. 我注意到仅在填充最高有效位时才会出现此问题。 If I change the inputs '8'to a '7' I get the correct output of: "I just wrote the value: 710c0001" What are some things I can do to read in the correct value? 如果将输入“ 8”更改为“ 7”,我将得到以下正确输出:“我刚刚写入了值:710c0001”我可以做些什么来读取正确的值? Thank you 谢谢

That's because int size is 4bytes which means it can only store values from -2,147,483,648 to 2,147,483,647. 那是因为int大小为4bytes,这意味着它只能存储从-2,147,483,648到2,147,483,647的值。

7fffffff=2,147,483,647 7FFFFFFF = 2147483647

The value 0x810c0001 is out of range. 0x810c0001值超出范围。 You can change the variable type to unsigned int to be able to store larger values in a case that you only care about positive numbers. 您可以将变量类型更改为unsigned int ,以便在只关心正数的情况下能够存储较大的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM