BitUtils.cs 1.5 KB

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