LittleEndianBitConverter.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. namespace MiscUtil.Conversion
  2. {
  3. /// <summary>
  4. /// Implementation of EndianBitConverter which converts to/from little-endian
  5. /// byte arrays.
  6. /// </summary>
  7. public sealed class LittleEndianBitConverter : EndianBitConverter
  8. {
  9. /// <summary>
  10. /// Indicates the byte order ("endianess") in which data is converted using this class.
  11. /// </summary>
  12. /// <remarks>
  13. /// Different computer architectures store data using different byte orders. "Big-endian"
  14. /// means the most significant byte is on the left end of a word. "Little-endian" means the
  15. /// most significant byte is on the right end of a word.
  16. /// </remarks>
  17. /// <returns>true if this converter is little-endian, false otherwise.</returns>
  18. public sealed override bool IsLittleEndian()
  19. {
  20. return true;
  21. }
  22. /// <summary>
  23. /// Indicates the byte order ("endianess") in which data is converted using this class.
  24. /// </summary>
  25. public sealed override Endianness Endianness
  26. {
  27. get { return Endianness.LittleEndian; }
  28. }
  29. /// <summary>
  30. /// Copies the specified number of bytes from value to buffer, starting at index.
  31. /// </summary>
  32. /// <param name="value">The value to copy</param>
  33. /// <param name="bytes">The number of bytes to copy</param>
  34. /// <param name="buffer">The buffer to copy the bytes into</param>
  35. /// <param name="index">The index to start at</param>
  36. protected override void CopyBytesImpl(long value, int bytes, byte[] buffer, int index)
  37. {
  38. for (int i=0; i < bytes; i++)
  39. {
  40. buffer[i+index] = unchecked((byte)(value&0xff));
  41. value = value >> 8;
  42. }
  43. }
  44. /// <summary>
  45. /// Returns a value built from the specified number of bytes from the given buffer,
  46. /// starting at index.
  47. /// </summary>
  48. /// <param name="buffer">The data in byte array format</param>
  49. /// <param name="startIndex">The first index to use</param>
  50. /// <param name="bytesToConvert">The number of bytes to use</param>
  51. /// <returns>The value built from the given bytes</returns>
  52. protected override long FromBytes(byte[] buffer, int startIndex, int bytesToConvert)
  53. {
  54. long ret = 0;
  55. for (int i=0; i < bytesToConvert; i++)
  56. {
  57. ret = unchecked((ret << 8) | buffer[startIndex+bytesToConvert-1-i]);
  58. }
  59. return ret;
  60. }
  61. }
  62. }