A base-two logarithm gives the exponent you put on 2 to get a positive number.
dotnet add package RecursiveAI.OneMathRequires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.
using RecursiveAI.OneMath; Console.WriteLine(Math64.Log2(8)); Console.WriteLine(Math64.Log2(0.5));
Unzip the example, then dotnet run.
Prints:
3 -1
The full program
using RecursiveAI.OneMath; double[] inputs = [0.125, 0.5, 1, 2, 8, 1024, 3, 0, -1]; foreach (double x in inputs) { double result = Math64.Log2(x); Console.WriteLine(FormattableString.Invariant( $"log2({x:R}) = {result:R}")); }
log2(0.125) = -3 log2(0.5) = -1 log2(1) = 0 log2(2) = 1 log2(8) = 3 log2(1024) = 10 log2(3) = 1.584962500721156 log2(0) = -Infinity log2(-1) = NaN
Log2 returns a floating-point logarithm, not an integer exponent with the fractional part dropped.
Zero returns negative infinity, and negative inputs return NaN; if you need a finite real result, require a positive, finite input.
Variations
Use single precision. Math32.Log2 rounds the result to float:
using RecursiveAI.OneMath; float exponent = Math32.Log2(1024f); Console.WriteLine(exponent);
This prints 10.
Related recipes
The short answer
Call Math64.Log2(x) for a deterministic base-two logarithm of a double in C#. OneMath’s function contract specifies correct rounding and bit-identical results across platforms for the same input bits. Use the dedicated Log2 call rather than dividing two separately rounded natural logs when you want the correctly rounded base-two result.
What is log base 2?
log₂(x) answers “2 raised to what power equals x?” In the example, 8 gives 3 because 2³ is 8. Likewise, ½ gives −1 because 2⁻¹ is ½, and 1 gives 0 because 2⁰ is 1. A positive input below 1 therefore has a negative logarithm; a negative result doesn’t mean the input itself was negative.
For a number that isn’t a power of two, the answer can fall between integers. For example, 3 is between 2 and 4, so its logarithm is between 1 and 2; the program prints 1.584962500721156. Keep the fractional part if your calculation needs the logarithm itself. If you need an integer, decide separately whether you mean the power below the input or the one above it. Casting a negative result to int truncates toward zero, not down.
Is log automatically base 2?
Not in OneMath. Math64.Log is the natural logarithm (base e), Math64.Log10 is base ten, and Math64.Log2 is base two. The base changes the answer, not the way the input is written: 1024 in the C# call is an ordinary decimal literal, and Log2 returns 10 because 2¹⁰ is 1024.
The function reference describes how the base-two path splits the input into a power of two and a factor from 1 to just below 2. That separates the whole-power contribution from the fractional contribution before rounding the result. The determinism applies to the stored input, not to the arithmetic that produced it: if your callers round a value differently before passing it in, they’re no longer asking for the logarithm of the same number.