BitArrayStream.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. using System;
  2. using System.Collections;
  3. namespace Ryujinx.Graphics.Texture
  4. {
  5. public class BitArrayStream
  6. {
  7. public BitArray BitsArray;
  8. public int Position { get; private set; }
  9. public BitArrayStream(BitArray bitArray)
  10. {
  11. BitsArray = bitArray;
  12. Position = 0;
  13. }
  14. public short ReadBits(int length)
  15. {
  16. int retValue = 0;
  17. for (int i = Position; i < Position + length; i++)
  18. {
  19. if (BitsArray[i])
  20. {
  21. retValue |= 1 << (i - Position);
  22. }
  23. }
  24. Position += length;
  25. return (short)retValue;
  26. }
  27. public int ReadBits(int start, int end)
  28. {
  29. int retValue = 0;
  30. for (int i = start; i <= end; i++)
  31. {
  32. if (BitsArray[i])
  33. {
  34. retValue |= 1 << (i - start);
  35. }
  36. }
  37. return retValue;
  38. }
  39. public int ReadBit(int index)
  40. {
  41. return Convert.ToInt32(BitsArray[index]);
  42. }
  43. public void WriteBits(int value, int length)
  44. {
  45. for (int i = Position; i < Position + length; i++)
  46. {
  47. BitsArray[i] = ((value >> (i - Position)) & 1) != 0;
  48. }
  49. Position += length;
  50. }
  51. public byte[] ToByteArray()
  52. {
  53. byte[] retArray = new byte[(BitsArray.Length + 7) / 8];
  54. BitsArray.CopyTo(retArray, 0);
  55. return retArray;
  56. }
  57. public static int Replicate(int value, int numberBits, int toBit)
  58. {
  59. if (numberBits == 0) return 0;
  60. if (toBit == 0) return 0;
  61. int tempValue = value & ((1 << numberBits) - 1);
  62. int retValue = tempValue;
  63. int resLength = numberBits;
  64. while (resLength < toBit)
  65. {
  66. int comp = 0;
  67. if (numberBits > toBit - resLength)
  68. {
  69. int newShift = toBit - resLength;
  70. comp = numberBits - newShift;
  71. numberBits = newShift;
  72. }
  73. retValue <<= numberBits;
  74. retValue |= tempValue >> comp;
  75. resLength += numberBits;
  76. }
  77. return retValue;
  78. }
  79. public static int PopCnt(int number)
  80. {
  81. int counter;
  82. for (counter = 0; number != 0; counter++)
  83. {
  84. number &= number - 1;
  85. }
  86. return counter;
  87. }
  88. public static void Swap<T>(ref T lhs, ref T rhs)
  89. {
  90. T temp = lhs;
  91. lhs = rhs;
  92. rhs = temp;
  93. }
  94. // Transfers a bit as described in C.2.14
  95. public static void BitTransferSigned(ref int a, ref int b)
  96. {
  97. b >>= 1;
  98. b |= a & 0x80;
  99. a >>= 1;
  100. a &= 0x3F;
  101. if ((a & 0x20) != 0) a -= 0x40;
  102. }
  103. }
  104. }