Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Definition of large integer value

Tags:

c++

casting

int64

I have a project where I deal with large numbers (ns-timestamps) that don't fit in an integer. I therefore want to to use e.g. int64_t and am currently writing a test case (yes!).

To check the behaviour for large number, i started with something like

int64_t val = 2*std::numeric_limits<int>::max();
qDebug() << "long val" << val;

which returns

long val -2

(same as if i define val as int).

But if I write

int64_t val = std::numeric_limits<int>::max();
val *= 2;
qDebug() << "long val" << val;

I get

long val 4294967294

which looks correct.

So for me it looks as if the 2*max() is first stored in an integer (truncated in this step) and then copied to the int64. Why does this happen? The compiler knows that the result is of type int64 so that it the 2*max() should fit directly.

like image 288
FooTheBar Avatar asked Jul 08 '14 09:07

FooTheBar


People also ask

What is a large integer?

A large integer is a binary integer with a precision of 31 bits. The range of large integers is -2147483648 to +2147483647.

What is defined as a large number?

Large numbers are numbers that are more significant than the ones we use on a regular basis. Large numbers are numbers that are generally larger or greater than other numbers in the number system.

What are integer values?

An integer (pronounced IN-tuh-jer) is a whole number (not a fractional number) that can be positive, negative, or zero. Examples of integers are: -5, 1, 5, 8, 97, and 3,043. Examples of numbers that are not integers are: -1.43, 1 3/4, 3.14, .

What is long integer value?

Long (long integer) variables are stored as signed 32-bit (4-byte) numbers ranging in value from -2,147,483,648 to 2,147,483,647.


1 Answers

So for me it looks as if the 2*max() is first stored in an integer (truncated in this step) and then copied to the int64

This is absolutely correct. According to the language specification, when all parts of an expression fit in an int, the computation is done in integers. In your case, both 2 and max() do fit in an int, so the multiplication is done in integers, causing an overflow.

The compiler knows that the result is of type int64 so that it the 2*max() should fit directly.

The result to which an expression is assigned does not matter in this situation: the expression itself directs the way it is calculated. You can achieve the same result by casting the max() to int64:

int64_t val = 2*(int64_t)std::numeric_limits<int>::max();
like image 163
Sergey Kalinichenko Avatar answered Oct 05 '22 12:10

Sergey Kalinichenko