Advertisement
NPSF3000

Two Numbers in One

Aug 28th, 2012
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.57 KB | None | 0 0
  1. //Storing two numbers in an integer.
  2. //http://forum.unity3d.com/threads/149073-PAID-Junior-Unity-developer-required-Full-time?p=1021224&viewfull=1#post1021224
  3.  
  4. // I quite like:
  5. var i = int.Parse(Console.ReadLine()) << 16;
  6. i |= 65535 & int.Parse(Console.ReadLine());
  7. Console.WriteLine((i >> 16));
  8. Console.WriteLine((i << 16) >> 16);
  9.  
  10. //Or if you are afraid of bitwise operators:
  11. var i = BitConverter.ToInt32(
  12.      BitConverter.GetBytes(short.Parse(Console.ReadLine()))
  13.     .Concat(
  14.      BitConverter.GetBytes(short.Parse(Console.ReadLine()))).ToArray(),
  15.      0);
  16.  
  17. Console.WriteLine(BitConverter.ToInt16(BitConverter.GetBytes(i), 0));
  18. Console.WriteLine(BitConverter.ToInt16(BitConverter.GetBytes(i), 2));
  19.  
  20.  
  21. //Or if you like variable length data:
  22. //http://stackoverflow.com/questions/11979184/reading-bit-aligned-data/11979287#11979287
  23.  
  24. //The following is useful for large quantities of data:
  25. var i = new int[1];
  26. Buffer.BlockCopy(new[] { short.Parse(Console.ReadLine()), short.Parse(Console.ReadLine()) }, 0, i, 0, 4);
  27. var s = new short[2];
  28. Buffer.BlockCopy(i, 0, s, 0, 4);
  29. Console.WriteLine(s[0]);
  30. Console.WriteLine(s[1]);
  31.  
  32.  
  33. //Oh, and here's a trick I bet they never taught you in school:
  34. var mi = new MyInteger { a = short.Parse(Console.ReadLine()), b = short.Parse(Console.ReadLine()) };
  35. var mi2 = new MyInteger { i = mi.i };
  36. Console.WriteLine(mi2.a);
  37. Console.WriteLine(mi2.b);
  38. ...
  39.  
  40. [StructLayout(LayoutKind.Explicit)]
  41. struct MyInteger
  42. {
  43.     [FieldOffset(0)]
  44.     public int i;
  45.     [FieldOffset(0)]
  46.     public short a;
  47.     [FieldOffset(2)]
  48.     public short b;
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement