There are a lot of questions about this on StackOverflow. A lot. However I cannot find an answer that:
The fastest way to get most significant bit at IL code should be a float
conversion and accessing the exponent bits.
Save code:
int myint = 7;
int msb = (BitConverter.SingleToInt32Bits(myint) >> 23) - 0x7f;
An even faster way would be the msb
and lsb
cpu instructions. As mentioned by phuclv it got availibele at .Net Core 3.0 so I affffded a test that is unfortunately not much faster.
As requested here are the BenchmarkDotNet results for 10000 coverts of uint
and ulong
. The speedup was factor 2 so the BitScanner solution is fast, but can't beat native float conversion.
Method | Mean | Error | StdDev | Ratio
BitScannerForward | 34.37 us | 0.420 us | 0.372 us | 1.00
BitConverterULong | 18.59 us | 0.238 us | 0.223 us | 0.54
BitConverterUInt | 18.58 us | 0.129 us | 0.121 us | 0.54
NtdllMsbCall | 31.34 us | 0.204 us | 0.170 us | 0.91
LeadingZeroCount | 15.85 us | 0.169 us | 0.150 us | 0.48