convert from long long to int and the other way back in c++

Loers Antario picture Loers Antario · Aug 20, 2012 · Viewed 91.2k times · Source

How to convert from long long to int and the other way back in c++ ?? also what are the properties of long long , especially its maximum size, thank in advance ..

Answer

Keith Thompson picture Keith Thompson · Jan 23, 2015

int is guaranteed to be at least 16 bits wide. On modern systems, it's most commonly 32 bits (even on 64-bit systems).

long long, which didn't originally exist in C++, is guaranteed to be at least 64 bits wide. It's almost always exactly 64 bits wide.

The usual way to convert a value from one integer type to another is simply to assign it. Any necessary conversion will be done implicitly. For example:

int x = 42;
long long y = 9223372036854775807;
y = x; // implicitly converts from int to long long
x = y; // implicitly converts from long long to int

For a narrowing conversion, where the target type can't represent all the values of the source type, there's a risk of overflow; int may or may not be able to hold the value 9223372036854775807. In this case, the result is implementation-defined. The most likely behavior is that the high-order bits are discarded; for example, converting 9223372036854775807 to int might yield 2147483647. (This is clearer in hexadecimal; the values are 0x7fffffffffffffff and 0x7fffffff, respectively.)

If you need to convert explicitly, you can use a cast. A C-style cast uses the type name in parentheses:

(long long)x

Or you can use a C++-style static_cast:

static_cast<long long>(x)

which is somewhat safer than a C-style cast because it's restricted in which types it can operate on.