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