// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Runtime.InteropServices; namespace E { [StructLayout(LayoutKind.Explicit)] internal struct IntLong { [FieldOffset(0)] public int lowintval; [FieldOffset(4)] public int highintval; [FieldOffset(0)] public long longval; } public class MainClass { public static long ToInt64_Bytes(int high, int low) { byte[] highBytes = BitConverter.GetBytes(high); byte[] lowBytes = BitConverter.GetBytes(low); byte[] bytes = new Byte[8]; Array.Copy(highBytes, 0, bytes, 4, 4); Array.Copy(lowBytes, 0, bytes, 0, 4); return BitConverter.ToInt64(bytes, 0); } public static long ToInt64_Arith(int high, int low) { return high * 0x100000000L + (uint)low; } public static long ToInt64_Shift(int high, int low) { return (((long)high)<<32) | (uint)low; } private static IntLong cvt; public static long ToInt64_Union(int high, int low) { cvt.highintval = high; cvt.lowintval = low; return cvt.longval; } public unsafe static long ToInt64_Pointer(int high, int low) { long res; *(((int *)&res)+1) = high; *((int *)&res) = low; return res; } private const int N = 200000000; public static void Main(string[] args) { Random rng = new Random(); for(int i = 0; i < 1000; i++) { byte[] b = new byte[8]; rng.NextBytes(b); long v = BitConverter.ToInt64(b, 0); int vhigh = (int)(v >> 32); int vlow = (int)v; long v2 = ToInt64_Bytes(vhigh, vlow); if(v2 != v) { Console.WriteLine("Bytes: " + v + " -> " + v2); } long v3 = ToInt64_Arith(vhigh, vlow); if(v3 != v) { Console.WriteLine("Arith: " + v + " -> " + v3); } long v4 = ToInt64_Shift(vhigh, vlow); if(v4 != v) { Console.WriteLine("Shift: " + v + " -> " + v4); } long v5 = ToInt64_Union(vhigh, vlow); if(v5 != v) { Console.WriteLine("Union: " + v + " -> " + v5); } long v6 = ToInt64_Pointer(vhigh, vlow); if(v6 != v) { Console.WriteLine("Pointer: " + v + " -> " + v6); } } DateTime t1 = DateTime.Now; for(int i = 0; i < N; i++) { ToInt64_Bytes(12345,67890); } DateTime t2 = DateTime.Now; Console.WriteLine("Bytes: " + (t2 - t1).TotalSeconds); DateTime t3 = DateTime.Now; for(int i = 0; i < N; i++) { ToInt64_Arith(12345,67890); } DateTime t4 = DateTime.Now; Console.WriteLine("Arith: " + (t4 - t3).TotalSeconds); DateTime t5 = DateTime.Now; for(int i = 0; i < N; i++) { ToInt64_Shift(12345,67890); } DateTime t6 = DateTime.Now; Console.WriteLine("Shift: " + (t6 - t5).TotalSeconds); DateTime t7 = DateTime.Now; for(int i = 0; i < N; i++) { ToInt64_Union(12345,67890); } DateTime t8 = DateTime.Now; Console.WriteLine("Union: " + (t8 - t7).TotalSeconds); DateTime t9 = DateTime.Now; for(int i = 0; i < N; i++) { ToInt64_Pointer(12345,67890); } DateTime t10 = DateTime.Now; Console.WriteLine("Pointer: " + (t10 - t9).TotalSeconds); } } }