开发者

Comparing two Hexadecimal values in C++

I want to compare two hexadecimal(stored in long) below is my code

long constant = 80040e14;
if(constant == 80040e14)
    cout<<"Success"<<endl;
else
    cout<<"Fail!!"<<endl;

In this code flow control always returns to else part, can anyone please suggest how to proceed with the comparison.

Than开发者_运维百科ks

Santhosha K


Prefix your constants with '0x'.

Your constant only has 'e' in it and the compiler will treat numbers of the form: NNNeEEE as scientific notation. Using the '0x' prefix tells the compiler that the following characters are in hexadecimal notation.

In your code, 80040e14 is 8004000000000000000 which is way too big to fit into 32bit value but can fit into a 64bit value. But, 80040e14 is a floating point number so the comparison will convert the long to a float to make it the same type as the constant and so the two values will be different due to the complexities of floating point code.


You need to put 0x in front of your hexadecimal numbers in C++


For hexadecimal values you need to prefix the constant with 0x Otherwise e is taken as an exponent and the value is interpreted as a huge decimal value. In your cases, most probably this value can not be stored in a long and it overflows. Because of this overflow, your comparison check fails.


To compare two values use the == operator. The only thing to consider is telling the compiler which base is the value using:

  • Decimal: write the number as always you do in "real life". Example: 1 (one), 2 (two), 3 (three), ...

  • Hexadecimal: You must append 0x to the value. Example: 0x01 (one), 0x02 (two), 0x03 (three), ...

  • Binary: Append 0b. Example: 0b01 (one), 0xb10 (two), 0b11 (three). Edit: seems like this isn't true. Don't trust in this feature.

In your example, just do:

long constant = 0x80040e14;
if(constant == 0x80040e14L)
    cout<<"Success"<<endl;
else
    cout<<"Fail!!"<<endl;


Do you want to compare a hex?
Use 0x80040e14 -> notice the 0x prefix to let the compiler know it is hexadecimal format.

The way you write it the compiler may try to parse it as a float (e meaning exponential), but I did not actually try it to see how it handles this.


80040e14 is a double. When assigned to a long it becomes zero. 80040e14L is a long double. the expression

constant == 80040e14L

promotes constant to a long double so you have

0.0 == 80040e14
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜