## [Math] IEEE 754 exponent as binary logarithm

Nicely written about binary logarithm function, which 'returns the binary exponent':

Function: logb x

This function returns the binary exponent of x. More precisely, if x is finite and nonzero, the value is the logarithm base 2 of |x|, rounded down to an integer. If x is zero or infinite, the value is infinity; if x is a NaN, the value is a NaN.

(logb 10)
⇒ 3
(logb 10.0e20)
⇒ 69
(logb 0)
⇒ -1.0e+INF


It's indeed so. IEEE 754 usually encoded in binary, including exponent.

Let's grind out the exponent from the single-precision IEEE 754 number:

// copypasted from https://stackoverflow.com/questions/15685181/how-to-get-the-sign-mantissa-and-exponent-of-a-floating-point-number
#include <stdio.h>
#include <stdlib.h>

typedef union
{
float f;
struct {
unsigned int mantisa : 23;
unsigned int exponent : 8;
unsigned int sign : 1;
} parts;
} float_cast;

int main(int argc, char *argv[])
{
int x = strtod(argv[1], NULL);
float_cast d1 = { .f = x };
printf("sign = %d\n", d1.parts.sign);
printf("exponent = %d\n", d1.parts.exponent);
// https://en.wikipedia.org/wiki/Exponent_bias
printf("exponent-exponent_bias(127) = %d\n", d1.parts.exponent-127);
printf("mantisa = %d\n", d1.parts.mantisa);
}

% ./a.out 123456
sign = 0
exponent = 143
exponent-exponent_bias(127) = 16
mantisa = 7413760


Yes:

% python3
>>> import math
>>> math.log(123456, 2)
16.913637428049103

And this is nice, zero mantissa:
% ./a.out 1024
sign = 0
exponent = 137
exponent-exponent_bias(127) = 10
mantisa = 0

% ./a.out 65536
sign = 0
exponent = 143
exponent-exponent_bias(127) = 16
mantisa = 0

...


Calculate: $$2^{10}=1024$$, $$2^{16}=65536$$.

Also, all this can be checked with the online IEEE 754 calculator.

###### (the post first published at 20240525.)

Yes, I know about these lousy Disqus ads. Please use adblocker. I would consider to subscribe to 'pro' version of Disqus if the signal/noise ratio in comments would be good enough.