Advertisement
Guest User

Untitled

a guest
Apr 18th, 2014
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. .ToBytes(UInt64 value, Byte[] array, Int32 offset);
  2. .ToBytes(UInt16 value, Byte[] array, Int32 offset);
  3.  
  4. public unsafe static byte[] GetBytes(long value)
  5. {
  6. byte[] array = new byte[8];
  7. fixed (byte* ptr = array)
  8. {
  9. *(long*)ptr = value;
  10. }
  11. return array;
  12. }
  13.  
  14. static unsafe void ToBytes(ulong value, byte[] array, int offset)
  15. {
  16. fixed (byte* ptr = &array[offset])
  17. *(ulong*)ptr = value;
  18. }
  19.  
  20. byte[] array = new byte[9];
  21. ToBytes(0x1122334455667788, array, 1);
  22.  
  23. static void ToBytes(ulong value, byte[] array, int offset)
  24. {
  25. byte[] valueBytes = BitConverter.GetBytes(value);
  26. Array.Copy(valueBytes, 0, array, offset, valueBytes.Length);
  27. }
  28.  
  29. static void ToBytes(ulong value, byte[] array, int offset)
  30. {
  31. for (int i = 0; i < 8; i++)
  32. {
  33. array[offset + i] = (byte)value;
  34. value >>= 8;
  35. }
  36. }
  37.  
  38. static void ToBytes(ulong value, byte[] array, int offset) {
  39. unchecked {
  40. array[offset + 0] = (byte)(value >> (8*7));
  41. array[offset + 1] = (byte)(value >> (8*6));
  42. array[offset + 2] = (byte)(value >> (8*5));
  43. array[offset + 3] = (byte)(value >> (8*4));
  44. //...
  45. }
  46. }
  47.  
  48. static class Extensions
  49. {
  50. public static void ToBytes(this int n, byte[] destination, int offset)
  51. {
  52. var data = BitConverter.GetBytes(n);
  53. Array.Copy(data, 0, destination, offset, data.Length);
  54. }
  55. }
  56.  
  57. byte[] destination = new byte[10];
  58.  
  59. 123.ToBytes(destination,0);
  60.  
  61. public static void ToBytes(ulong value, byte[] array, int offset)
  62. {
  63. GCHandle handle = GCHandle.Alloc(value, GCHandleType.Pinned);
  64. try
  65. {
  66. Marshal.Copy(handle.AddrOfPinnedObject(), array, offset, 8);
  67. }
  68. finally
  69. {
  70. handle.Free();
  71. }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement