Converting __int64 to long in Windows

15,443

Solution 1

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.

Solution 2

Yes, typecasting will be fine, so long as you can guarantee your __int64 values are always within the range of a long. Casting in the other direction, i.e. from long to __int64 will not be a problem regardless of the values involved.

Solution 3

Here is a small test. The explicit casts are necessary to avoid the warnings if compiled with /W3:

#include <limits.h>


int main( int argc, char *argv[] )
{
    __int64 i64;
    long i;

    i64 = -1;
    i = (long)i64;
    printf( "i=%d\n", i );

    i64 = INT_MAX;
    i = (long)i64;
    printf( "i=%d\n", i );

    i64 = INT_MIN;
    i = (long)i64;
    printf( "i=%d\n", i );

    i64 = i;
    printf( "i64=%I64d\n", i64 );
}

The output is:

i=-1
i=2147483647
i=-2147483648
i64=-2147483648
Share:
15,443
Jay
Author by

Jay

Just another learner interested in programming! : )

Updated on June 04, 2022

Comments

  • Jay
    Jay almost 2 years

    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.