BitUtils.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. using System.Runtime.CompilerServices;
  2. namespace ARMeilleure.Common
  3. {
  4. static class BitUtils
  5. {
  6. private const int DeBrujinSequence = 0x77cb531;
  7. private static int[] DeBrujinLbsLut;
  8. static BitUtils()
  9. {
  10. DeBrujinLbsLut = new int[32];
  11. for (int index = 0; index < DeBrujinLbsLut.Length; index++)
  12. {
  13. uint lutIndex = (uint)(DeBrujinSequence * (1 << index)) >> 27;
  14. DeBrujinLbsLut[lutIndex] = index;
  15. }
  16. }
  17. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  18. public static int LowestBitSet(int value)
  19. {
  20. if (value == 0)
  21. {
  22. return -1;
  23. }
  24. int lsb = value & -value;
  25. return DeBrujinLbsLut[(uint)(DeBrujinSequence * lsb) >> 27];
  26. }
  27. public static int HighestBitSet(int value)
  28. {
  29. if (value == 0)
  30. {
  31. return -1;
  32. }
  33. for (int bit = 31; bit >= 0; bit--)
  34. {
  35. if (((value >> bit) & 1) != 0)
  36. {
  37. return bit;
  38. }
  39. }
  40. return -1;
  41. }
  42. private static readonly sbyte[] HbsNibbleLut = { -1, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3 };
  43. public static int HighestBitSetNibble(int value) => HbsNibbleLut[value & 0b1111];
  44. public static long Replicate(long bits, int size)
  45. {
  46. long output = 0;
  47. for (int bit = 0; bit < 64; bit += size)
  48. {
  49. output |= bits << bit;
  50. }
  51. return output;
  52. }
  53. public static int CountBits(int value)
  54. {
  55. int count = 0;
  56. while (value != 0)
  57. {
  58. value &= ~(value & -value);
  59. count++;
  60. }
  61. return count;
  62. }
  63. public static long FillWithOnes(int bits)
  64. {
  65. return bits == 64 ? -1L : (1L << bits) - 1;
  66. }
  67. public static int RotateRight(int bits, int shift, int size)
  68. {
  69. return (int)RotateRight((uint)bits, shift, size);
  70. }
  71. public static uint RotateRight(uint bits, int shift, int size)
  72. {
  73. return (bits >> shift) | (bits << (size - shift));
  74. }
  75. public static long RotateRight(long bits, int shift, int size)
  76. {
  77. return (long)RotateRight((ulong)bits, shift, size);
  78. }
  79. public static ulong RotateRight(ulong bits, int shift, int size)
  80. {
  81. return (bits >> shift) | (bits << (size - shift));
  82. }
  83. }
  84. }