BitUtils.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System.Numerics;
  2. namespace ARMeilleure.Common
  3. {
  4. static class BitUtils
  5. {
  6. private static readonly sbyte[] HbsNibbleLut;
  7. static BitUtils()
  8. {
  9. HbsNibbleLut = new sbyte[] { -1, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3 };
  10. }
  11. public static int CountBits(int value)
  12. {
  13. int count = 0;
  14. while (value != 0)
  15. {
  16. value &= ~(value & -value);
  17. count++;
  18. }
  19. return count;
  20. }
  21. public static long FillWithOnes(int bits)
  22. {
  23. return bits == 64 ? -1L : (1L << bits) - 1;
  24. }
  25. public static int HighestBitSet(int value)
  26. {
  27. return 31 - BitOperations.LeadingZeroCount((uint)value);
  28. }
  29. public static int HighestBitSetNibble(int value)
  30. {
  31. return HbsNibbleLut[value];
  32. }
  33. public static long Replicate(long bits, int size)
  34. {
  35. long output = 0;
  36. for (int bit = 0; bit < 64; bit += size)
  37. {
  38. output |= bits << bit;
  39. }
  40. return output;
  41. }
  42. public static int RotateRight(int bits, int shift, int size)
  43. {
  44. return (int)RotateRight((uint)bits, shift, size);
  45. }
  46. public static uint RotateRight(uint bits, int shift, int size)
  47. {
  48. return (bits >> shift) | (bits << (size - shift));
  49. }
  50. public static long RotateRight(long bits, int shift, int size)
  51. {
  52. return (long)RotateRight((ulong)bits, shift, size);
  53. }
  54. public static ulong RotateRight(ulong bits, int shift, int size)
  55. {
  56. return (bits >> shift) | (bits << (size - shift));
  57. }
  58. }
  59. }