Converting __int64 to long in Windows

Jay picture Jay · Feb 8, 2010 · Viewed 15.1k times · Source

How to convert __int64 to long in Windows (MSVC8 & MSVC6)?

Will a normal typecasting work?

Also, how about converting long to __int64? If the long is a negative value, will it work?

Note - I am talking of a scenario in which the __int64 variable will always contain a value which will not be more than 32 bits long.

Answer

Jichao picture Jichao · Feb 8, 2010

1. Convert long to __int64

Acorrding to MSDN on the __int64 keyword:

The _ _int64 keyword declares a new type, a 64-bit (8-byte) integer. As with the int, short, and long types, the _ _int64 type has a corresponding unsigned version, so the _ _int64 keyword actually can be used to create two types.

The following code sample shows how to declare two 64-bit integers, one signed and the other unsigned:

__int64 signed_big_int; unsigned __int64 unsigned_big_int;

__int64 is signed,and it should be wider than long.So you could assign long to __int64 without even a type cast and of course the signed __int64 support negative long.

2. Convert __int64 to long

It is OK to convert __int64 to long,only with possibility of loosing data.My msvc8 only warn me of the pssibility of loss of data.

3. Note:

C99 defined a standard 64-bit integer type named int64_t and unsigned version uint64_t in stdint.h.If you want to provide portable code, you should use them but not __int64.

Notice there is no standard 64-bit integer type in C++ programming language,MSVC use __int64,but in linux world you normally use int64_t or uint64_t which is type defined as long long or unsigned long long in C99's stdint.h.Here I assume your C++ compiler support the stdint.h header file.