BinaryUtils.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using System;
  2. using System.IO;
  3. namespace SharpCompress.Compressors.Xz
  4. {
  5. public static class BinaryUtils
  6. {
  7. public static int ReadLittleEndianInt32(this BinaryReader reader)
  8. {
  9. byte[] bytes = reader.ReadBytes(4);
  10. return (bytes[0] + (bytes[1] << 8) + (bytes[2] << 16) + (bytes[3] << 24));
  11. }
  12. internal static uint ReadLittleEndianUInt32(this BinaryReader reader)
  13. {
  14. return unchecked((uint)ReadLittleEndianInt32(reader));
  15. }
  16. public static int ReadLittleEndianInt32(this Stream stream)
  17. {
  18. byte[] bytes = new byte[4];
  19. var read = stream.ReadFully(bytes);
  20. if (!read)
  21. {
  22. throw new EndOfStreamException();
  23. }
  24. return (bytes[0] + (bytes[1] << 8) + (bytes[2] << 16) + (bytes[3] << 24));
  25. }
  26. internal static uint ReadLittleEndianUInt32(this Stream stream)
  27. {
  28. return unchecked((uint)ReadLittleEndianInt32(stream));
  29. }
  30. internal static byte[] ToBigEndianBytes(this uint uint32)
  31. {
  32. var result = BitConverter.GetBytes(uint32);
  33. if (BitConverter.IsLittleEndian)
  34. Array.Reverse(result);
  35. return result;
  36. }
  37. internal static byte[] ToLittleEndianBytes(this uint uint32)
  38. {
  39. var result = BitConverter.GetBytes(uint32);
  40. if (!BitConverter.IsLittleEndian)
  41. Array.Reverse(result);
  42. return result;
  43. }
  44. }
  45. }