From a while back, but still interesting:
- [Wayback/Archive] Counting the leading zeroes in a binary number with C#
- [Wayback/Archive] c# – Getting the number of leading 1 bits – Stack Overflow (thanks [Wayback/Archive] Barry Kelly and [Wayback/Archive] SoapBox)
Especially the first link explains the algorithm very well and is similar to links referred to from the Stack Overflow question as it is based on counting ones (and leading ones are basically leading zeros but bit-inverted).
It also explains a cool thing for leading zeros: modern CPU have instructions which .NET Core.
Via:
- [Wayback/Archive] Andrew Lock “Sock” on Twitter: “Blogged: Counting the leading zeroes in a binary number with C# #dotnet #dotnetcore #csharp”
- [Wayback/Archive] Jeroen Wiert Pluimers on Twitter: “@andrewlocknet Cool. This is kind of the opposite I asked a few years back a @StackOverflow”
References:
- [Wayback/Archive] dd-trace-dotnet/VarEncodingHelper.cs at 635c879092089703ad6724bb70c96884f65cd631 · DataDog/dd-trace-dotnet
- [Wayback/Archive] c# – Count leading zeroes in an Int32 – Stack Overflow (thanks [Wayback/Archive] phuclv and [Wayback/Archive] spender)
- [Wayback/Archive] The Aggregate Magic Algorithms (which is basically THE goto page for bit fiddling algorithms) which for instance has these gems used in the above links
- [Wayback/Archive] runtime/BitOperations.cs at main · dotnet/runtime: LeadingZeroCount (the file has many more operations)
- [Wayback/Archive] c++ – Getting the number of trailing 1 bits – Stack Overflow
- Endianness – Wikipedia
- [Wayback/Archive] inet_addr function (winsock2.h) – Win32 apps | Microsoft Learn
- [Wayback/Archive] in_addr (winsock2.h) – Win32 apps | Microsoft Learn
--
jeroen