Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 ..

like image 711
Loers Antario Avatar asked Aug 20 '12 01:08

Loers Antario


People also ask

How do you convert long to Ulong?

To convert a long to a ulong, simply cast it: long a; ulong b = (ulong)a; C# will NOT throw an exception if it is a negative number.

Can we type cast long to int in C?

In terms of converting a ( signed ) long long datatype to an unsigned int in C and C++, you can simply cast the data between them: int main()

Can we use %d for long?

You should scanf for a %ld if that is what you are expecting. But since a long is larger than your typical int , there is no issue with this.


2 Answers

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.

like image 141
Keith Thompson Avatar answered Oct 06 '22 23:10

Keith Thompson


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.

like image 39
David Avatar answered Oct 06 '22 23:10

David