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 ..
Type long long is typically 64 bits.
Type int is likely to be 32 bits, but not on all machines.
If you cast an int to a long long, you can do
my_long_long = (long long) my_int
and it will be just fine. If you go the other direction, like
my_int = (int) my_long_long
and the int is smaller than 64-bits, it won't be able to hold all the information, so the result may not be correct.
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.
Size of int is only 2 bytes whereas the other one is usually larger than int. So if you are looking to convert long into int then you would end up loosing information. But the other way is possible without sacrificing the correctness of information.
Suppose a
is of long type and b
is of int type. Then int to long covertion:a=(long)b;
. For other way:b=(int)a;
.