Search code examples
c#.netlogarithm

How can I compute a base 2 logarithm without using the built-in math functions in C#?


How can I compute a base 2 logarithm without using the built-in math functions in C#?

I use Math.Log and BigInteger.Log repeatedly in an application millions of times and it becomes painfully slow.

I am interested in alternatives that use binary manipulation to achieve the same. Please bear in mind that I can make do with Log approximations in case that helps speed up execution times.


Solution

  • For the BigInteger you could use the toByteArray() method and then manually find the most significant 1 and count the number of zeroes afterward. This would give you the base-2 logarithm with integer precision.