ByteUtils.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using System;
  2. using System.IO;
  3. namespace Utilities
  4. {
  5. public class ByteUtils
  6. {
  7. public static byte[] Concatenate(byte[] a, byte[] b)
  8. {
  9. byte[] result = new byte[a.Length + b.Length];
  10. Array.Copy(a, 0, result, 0, a.Length);
  11. Array.Copy(b, 0, result, a.Length, b.Length);
  12. return result;
  13. }
  14. public static bool AreByteArraysEqual(byte[] array1, byte[] array2)
  15. {
  16. if (array1.Length != array2.Length)
  17. {
  18. return false;
  19. }
  20. for (int index = 0; index < array1.Length; index++)
  21. {
  22. if (array1[index] != array2[index])
  23. {
  24. return false;
  25. }
  26. }
  27. return true;
  28. }
  29. public static byte[] XOR(byte[] array1, byte[] array2)
  30. {
  31. if (array1.Length == array2.Length)
  32. {
  33. return XOR(array1, 0, array2, 0, array1.Length);
  34. }
  35. else
  36. {
  37. throw new ArgumentException("Arrays must be of equal length");
  38. }
  39. }
  40. public static byte[] XOR(byte[] array1, int offset1, byte[] array2, int offset2, int length)
  41. {
  42. if (offset1 + length <= array1.Length && offset2 + length <= array2.Length)
  43. {
  44. byte[] result = new byte[length];
  45. for (int index = 0; index < length; index++)
  46. {
  47. result[index] = (byte)(array1[offset1 + index] ^ array2[offset2 + index]);
  48. }
  49. return result;
  50. }
  51. else
  52. {
  53. throw new ArgumentOutOfRangeException();
  54. }
  55. }
  56. public static long CopyStream(Stream input, Stream output)
  57. {
  58. // input may not support seeking, so don't use input.Position
  59. return CopyStream(input, output, Int64.MaxValue);
  60. }
  61. public static long CopyStream(Stream input, Stream output, long count)
  62. {
  63. const int MaxBufferSize = 1048576; // 1 MB
  64. int bufferSize = (int)Math.Min(MaxBufferSize, count);
  65. byte[] buffer = new byte[bufferSize];
  66. long totalBytesRead = 0;
  67. while (totalBytesRead < count)
  68. {
  69. int numberOfBytesToRead = (int)Math.Min(bufferSize, count - totalBytesRead);
  70. int bytesRead = input.Read(buffer, 0, numberOfBytesToRead);
  71. totalBytesRead += bytesRead;
  72. output.Write(buffer, 0, bytesRead);
  73. if (bytesRead == 0) // no more bytes to read from input stream
  74. {
  75. return totalBytesRead;
  76. }
  77. }
  78. return totalBytesRead;
  79. }
  80. }
  81. }