MATLAB: Am I unable to correctly display 64-bit integers in MATLAB

6464-bitbitdatailp32integersMATLABmodel

Why am I unable to correctly display 64-bit integers in MATLAB?
I'm having trouble using 64-bit integer variable types in MEX functions. It seems that even though the compiler (Microsoft Visual C++) accepts __int54 as a type definition, the variable is still only 32 bits.
The following function demonstrates this example:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "mex.h"
#include "matrix.h"
typedef __int32 long32;
typedef __int64 long64;
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
long32 x_32;
long64 x_64;
x_32 = (long32)2147483648; // 2^31
x_64 = (long64)2147483648;
mexPrintf("x_32 = %d, x_64 = %d\n",x_32,x_64);
}
When run, this returns:
x_32 = -2147483648 x_64 = -2147483648

Best Answer

Win32 applications use the ILP32 Data Model, which specifies that (I)nt, (L)ong, and (P)ointers are all 32-bit entities. Thus, mexPrintf will not display the above integers correctly when you give the function a %d argument. This is because you are telling it to display an integer that is 32-bit.
To correctly display a 64-bit integer, you must give mexPrintf the %I64Ld augmented integer argument. Thus, changing the above code to read:
mexPrintf("x_32 = %I64Ld, x_64 = %I64Ld\n",x_32,x_64);
Will yield the correct result. The following is the output of compiling and running the mex:
>> mex long.c
>> long
x_32 = -9223372034707292160, x_64 = 101367855320137728
>>
As expected, the 32-bit integer overflows while the 64-bit integer is able to correctly display 2^31.