BigEndianBitConverter.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. namespace MiscUtil.Conversion
  2. {
  3. /// <summary>
  4. /// Implementation of EndianBitConverter which converts to/from big-endian
  5. /// byte arrays.
  6. /// </summary>
  7. public sealed class BigEndianBitConverter : 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 false;
  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.BigEndian; }
  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. int endOffset = index+bytes-1;
  39. for (int i=0; i < bytes; i++)
  40. {
  41. buffer[endOffset-i] = unchecked((byte)(value&0xff));
  42. value = value >> 8;
  43. }
  44. }
  45. /// <summary>
  46. /// Returns a value built from the specified number of bytes from the given buffer,
  47. /// starting at index.
  48. /// </summary>
  49. /// <param name="buffer">The data in byte array format</param>
  50. /// <param name="startIndex">The first index to use</param>
  51. /// <param name="bytesToConvert">The number of bytes to use</param>
  52. /// <returns>The value built from the given bytes</returns>
  53. protected override long FromBytes(byte[] buffer, int startIndex, int bytesToConvert)
  54. {
  55. long ret = 0;
  56. for (int i=0; i < bytesToConvert; i++)
  57. {
  58. ret = unchecked((ret << 8) | buffer[startIndex+i]);
  59. }
  60. return ret;
  61. }
  62. }
  63. }