BitUtils.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. namespace ChocolArm64.Decoders
  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 int RotateRight(int bits, int shift, int size)
  32. {
  33. return (int)RotateRight((uint)bits, shift, size);
  34. }
  35. public static uint RotateRight(uint bits, int shift, int size)
  36. {
  37. return (bits >> shift) | (bits << (size - shift));
  38. }
  39. public static long RotateRight(long bits, int shift, int size)
  40. {
  41. return (long)RotateRight((ulong)bits, shift, size);
  42. }
  43. public static ulong RotateRight(ulong bits, int shift, int size)
  44. {
  45. return (bits >> shift) | (bits << (size - shift));
  46. }
  47. }
  48. }