Build a 'long' number from two int's
Author Message
Georg W&amp;#228;chter

 Posted: Visual C# General, Build a 'long' number from two int's Top
 Hello,i'm wondering whether it is possible to "build" a long number from two int's. My aim is to make it platform independent, thus i can't use any shift operators. With them, i would do something like that:long number = (long)myInt | (((long)myInt2) << 32);Does anybody have an idea georg Visual C#12

mmix

 Posted: Visual C# General, Build a 'long' number from two int's Top
 Combining two ints into a long is very much a platform dependent operation. You could potentially encapsulate this operation by first discovering the endianess of the platform (using BitConverter.IsLittleEndian) and then using appropriate shifting sequence.

mmix

 Posted: Visual C# General, Build a 'long' number from two int's Top
 Actaully, the simplest solutions might actaully be the one. :) Instead of you worrying about endianess, let the JIT worry for you. Keep the casting to avoid leading 1's from messing your end result:               uint a1 = 4294967295;            uint a2 = 4294967295;            long x = (long)((ulong)a1 * (ulong)4294967296 + (ulong)a2);

Matthew Watson

 Posted: Visual C# General, Build a 'long' number from two int's Top
 The "endian-ness" of the platform should be hidden by .Net, so as far as I know the simple solution using shifts should work...

mmix

 Posted: Visual C# General, Build a 'long' number from two int's Top

 The "endian-ness" of the platform should be hidden by .Net, so as far as I know the simple solution using shifts should work...

At first I thought that you were wrong, but then I saw the err of my thinking. Their memory footprints are different, but the actual operation is math based, and is done in registers, and the storage mechanism doesnt affect the process at all as we are not operating over memory locations as we used to ages ago. So yes, I stand corrected, the below formula will work on both systems (cast is still needed to prevent negative i1 from messing up the result)

long l2 = (long)((ulong)i1 << 32 | i2);

That being said, what little-endian systems support .NET I havent heard of any yet...