当前位置:   article > 正文

C# 字节数组位操作_c#byte中位移动

c#byte中位移动
  1. public class BitBuffer
  2. {
  3. private byte[] m_data = null;
  4. private int m_dataLen = 0;
  5. private int m_pos = 0;
  6. public BitBuffer(byte[] data)
  7. {
  8. m_data = data;
  9. m_dataLen = data.Length;
  10. }
  11. public BitBuffer(byte[] data, int len)
  12. {
  13. m_data = data;
  14. m_dataLen = len;
  15. }
  16. public void Skip(int offset)
  17. {
  18. m_pos += offset;
  19. if (m_dataLen * 8 < m_pos)
  20. {
  21. throw new Exception("m_data.Length * 8 < m_offset");
  22. }
  23. }
  24. public int Read(int size, bool noseek = false)
  25. {
  26. int starBytePos = m_pos / 8;
  27. int starBitOffset = m_pos % 8;
  28. int starBitMask = 0;
  29. for (int i = 0; i < 8 - starBitOffset; ++i)
  30. {
  31. starBitMask <<= 1;
  32. starBitMask += 1;
  33. }
  34. int spanByte = (size + 7) / 8;
  35. if (4 < spanByte)
  36. {
  37. throw new Exception("4 < spanByte");
  38. }
  39. int value = 0;
  40. for (int i = 0; i < spanByte; ++i)
  41. {
  42. value <<= 8;
  43. value += m_data[starBytePos + i];
  44. if (0 == i)
  45. {
  46. value &= starBitMask;
  47. }
  48. }
  49. int endBitOffset = (m_pos + size) % 8;
  50. if (0 < endBitOffset)
  51. {
  52. value >>= (8 - endBitOffset);
  53. }
  54. if (!noseek)
  55. {
  56. Skip(size);
  57. }
  58. return value;
  59. }
  60. public byte[] ReadBytes(int size, bool noseek = false)
  61. {
  62. if (size <= 0)
  63. {
  64. return null;
  65. }
  66. byte[] temp = new byte[size / 8];
  67. Array.Copy(m_data, m_pos / 8, temp, 0, size / 8);
  68. if (!noseek)
  69. {
  70. Skip(size);
  71. }
  72. return temp;
  73. }
  74. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/112311
推荐阅读
  

闽ICP备14008679号