BitUtils.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 long FillWithOnes(int bits)
  12. {
  13. return bits == 64 ? -1L : (1L << bits) - 1;
  14. }
  15. public static int HighestBitSet(int value)
  16. {
  17. return 31 - BitOperations.LeadingZeroCount((uint)value);
  18. }
  19. public static int HighestBitSetNibble(int value)
  20. {
  21. return HbsNibbleLut[value];
  22. }
  23. public static long Replicate(long bits, int size)
  24. {
  25. long output = 0;
  26. for (int bit = 0; bit < 64; bit += size)
  27. {
  28. output |= bits << bit;
  29. }
  30. return output;
  31. }
  32. public static int RotateRight(int bits, int shift, int size)
  33. {
  34. return (int)RotateRight((uint)bits, shift, size);
  35. }
  36. public static uint RotateRight(uint bits, int shift, int size)
  37. {
  38. return (bits >> shift) | (bits << (size - shift));
  39. }
  40. public static long RotateRight(long bits, int shift, int size)
  41. {
  42. return (long)RotateRight((ulong)bits, shift, size);
  43. }
  44. public static ulong RotateRight(ulong bits, int shift, int size)
  45. {
  46. return (bits >> shift) | (bits << (size - shift));
  47. }
  48. }
  49. }