BitFlagsGenerator.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. namespace System.Runtime.Serialization
  3. {
  4. public class BitFlagsGenerator
  5. {
  6. int bitCount;
  7. byte [] locals;
  8. public BitFlagsGenerator (int bitCount)
  9. {
  10. this.bitCount = bitCount;
  11. int localCount = (bitCount+7)/8;
  12. locals = new byte [localCount];
  13. }
  14. public void Store (int bitIndex, bool value)
  15. {
  16. if (value)
  17. locals [GetByteIndex (bitIndex)] |= GetBitValue(bitIndex);
  18. else
  19. locals [GetByteIndex (bitIndex)] &= (byte) ~GetBitValue(bitIndex);
  20. }
  21. public bool Load (int bitIndex)
  22. {
  23. var local = locals[GetByteIndex(bitIndex)];
  24. byte bitValue = GetBitValue(bitIndex);
  25. return (local & bitValue) == bitValue;
  26. }
  27. public byte [] LoadArray ()
  28. {
  29. return (byte []) locals.Clone ();
  30. }
  31. public int GetLocalCount ()
  32. {
  33. return locals.Length;
  34. }
  35. public int GetBitCount ()
  36. {
  37. return bitCount;
  38. }
  39. public byte GetLocal (int i)
  40. {
  41. return locals [i];
  42. }
  43. public static bool IsBitSet (byte[] bytes, int bitIndex)
  44. {
  45. int byteIndex = GetByteIndex (bitIndex);
  46. byte bitValue = GetBitValue (bitIndex);
  47. return (bytes[byteIndex] & bitValue) == bitValue;
  48. }
  49. public static void SetBit (byte[] bytes, int bitIndex)
  50. {
  51. int byteIndex = GetByteIndex (bitIndex);
  52. byte bitValue = GetBitValue (bitIndex);
  53. bytes[byteIndex] |= bitValue;
  54. }
  55. static int GetByteIndex (int bitIndex)
  56. {
  57. return bitIndex >> 3;
  58. }
  59. static byte GetBitValue (int bitIndex)
  60. {
  61. return (byte)(1 << (bitIndex & 7));
  62. }
  63. }
  64. }