I have an int[2] representation of a long int in a 32 bit machine and want to convert it to long on 64bit machine. is there a safe architecture independent way of doing this conversion?
The source machine is 32bit and an int is 32bits. Destination machine is 64bit and the long long type is definitely 64bits.
can I do the following?
long i;
int j[2];
#ifdef LITTLEENDIAN
j[1] = *(int*)(&i);
j[0] = *(((int*)(&i))+1)
#else
j[0] = *(int*)(&i);
j[1] = *(((int*)(&i))+1)
#endif
If the above is incorrect, then what is the best and safest way for this? I am sure this would have been asked previously, but I didn’t find a clean answer.
Thanks
Not really. Because apart from endianness, the sizes of the two datatypes may vary as well. On some popular platforms,
intandlonghave the same size (both 32 bits)Ultimately, it depends on how you created your
int[2]representation. Whatever you did to create thatintarray has to be reversed in order to get a validlongout of it.One approach which will work in practice (but is, technically speaking, undefined behavior), is to place both in a union:
Now you can simply write to
u.i2and read fromu.l. The C++ standard technically doesn’t allow this (it is undefined behavior), but it is such a common trick that major compilers explicitly support it anyway.However, a better approach might be to use a
char[]instead ofint[], becausechar‘s are explicitly allowed to alias other types.