fork download
  1. using System;
  2.  
  3. class Program
  4. {
  5. public static void Main()
  6. {
  7. Console.WriteLine("IntPtr.Size: {0}", IntPtr.Size);
  8. Console.WriteLine();
  9.  
  10. // Two rounds, with positive and with negative numbers
  11. long test1 = 0x12340000 /* y */ | 0x00005678 /* x */;
  12. long test2 = 0xDCBA0000 /* y */ | 0x00009876 /* x */;
  13.  
  14. foreach (long temp in new[] { test1, test2})
  15. {
  16. long test = temp;
  17.  
  18. if (IntPtr.Size == 8)
  19. {
  20. // We "pad" the number so that all the 64 bits are full and a
  21. // standard (int)xy conversion will fail.
  22. test = unchecked((long)((ulong)test | 0xFFFFFFFF00000000ul));
  23. }
  24.  
  25. IntPtr xy = (IntPtr)test;
  26.  
  27. int x = unchecked((short)(long)xy);
  28. int y = unchecked((short)((long)xy >> 16));
  29.  
  30. // Other way, more similar to WinAPI
  31. ushort loword = unchecked((ushort)(ulong)xy);
  32. ushort hiword = unchecked((ushort)((ulong)xy >> 16));
  33.  
  34. int x2 = unchecked((int)(short)loword);
  35. int y2 = unchecked((int)(short)hiword);
  36.  
  37. Console.WriteLine("xy: {0:X}", unchecked((ulong)(long)xy));
  38. Console.WriteLine("x: {0:X}, decimal: {1}, other way: {2:X}, ushort other way: {3:X}", x, x, x2, unchecked((ushort)x2));
  39. Console.WriteLine("y: {0:X}, decimal: {1}, other way: {2:X}, ushort other way: {3:X}", y, y, y2, unchecked((ushort)y2));
  40. Console.WriteLine();
  41. }
  42. }
  43. }
Success #stdin #stdout 0.03s 33912KB
stdin
Standard input is empty
stdout
IntPtr.Size: 4

xy: 12345678
x: 5678, decimal: 22136, other way: 5678, ushort other way: 5678
y: 1234, decimal: 4660, other way: 1234, ushort other way: 1234

xy: FFFFFFFFDCBA9876
x: FFFF9876, decimal: -26506, other way: FFFF9876, ushort other way: 9876
y: FFFFDCBA, decimal: -9030, other way: FFFFDCBA, ushort other way: DCBA