BitUtils.cs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. namespace ChocolArm64
  2. {
  3. static class BitUtils
  4. {
  5. public static int HighestBitSet32(int value)
  6. {
  7. for (int bit = 31; bit >= 0; bit--)
  8. {
  9. if (((value >> bit) & 1) != 0)
  10. {
  11. return bit;
  12. }
  13. }
  14. return -1;
  15. }
  16. private static readonly sbyte[] HbsNibbleTbl = { -1, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3 };
  17. public static int HighestBitSetNibble(int value) => HbsNibbleTbl[value & 0b1111];
  18. public static long Replicate(long bits, int size)
  19. {
  20. long output = 0;
  21. for (int bit = 0; bit < 64; bit += size)
  22. {
  23. output |= bits << bit;
  24. }
  25. return output;
  26. }
  27. public static long FillWithOnes(int bits)
  28. {
  29. return bits == 64 ? -1L : (1L << bits) - 1;
  30. }
  31. public static long RotateRight(long bits, int shift, int size)
  32. {
  33. return (long)RotateRight((ulong)bits, shift, size);
  34. }
  35. public static ulong RotateRight(ulong bits, int shift, int size)
  36. {
  37. return (bits >> shift) | (bits << (size - shift));
  38. }
  39. }
  40. }