ABitUtils.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. namespace ChocolArm64
  2. {
  3. static class ABitUtils
  4. {
  5. public static int CountBitsSet(long Value)
  6. {
  7. int Count = 0;
  8. for (int Bit = 0; Bit < 64; Bit++)
  9. {
  10. Count += (int)(Value >> Bit) & 1;
  11. }
  12. return Count;
  13. }
  14. public static int HighestBitSet32(int Value)
  15. {
  16. for (int Bit = 31; Bit >= 0; Bit--)
  17. {
  18. if (((Value >> Bit) & 1) != 0)
  19. {
  20. return Bit;
  21. }
  22. }
  23. return -1;
  24. }
  25. private static readonly sbyte[] HbsNibbleTbl = { -1, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3 };
  26. public static int HighestBitSetNibble(int Value) => HbsNibbleTbl[Value & 0b1111];
  27. public static long Replicate(long Bits, int Size)
  28. {
  29. long Output = 0;
  30. for (int Bit = 0; Bit < 64; Bit += Size)
  31. {
  32. Output |= Bits << Bit;
  33. }
  34. return Output;
  35. }
  36. public static long FillWithOnes(int Bits)
  37. {
  38. return Bits == 64 ? -1L : (1L << Bits) - 1;
  39. }
  40. public static long RotateRight(long Bits, int Shift, int Size)
  41. {
  42. return (Bits >> Shift) | (Bits << (Size - Shift));
  43. }
  44. public static bool IsPow2(int Value)
  45. {
  46. return Value != 0 && (Value & (Value - 1)) == 0;
  47. }
  48. }
  49. }