ByteUtils.cs 2.9 KB

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