Packages

A utility library for calculating the bit length of integers in Elixir.

Current section

Files

Jump to
bit_length lib bit_length.ex
Raw

lib/bit_length.ex

defmodule BitLength do
@moduledoc """
A utility module for calculating the bit length of integers.
The bit length of an integer is the minimum number of bits required to represent
that integer in binary form, excluding leading zeros.
## Examples
iex> BitLength.of(0)
0
iex> BitLength.of(1)
1
iex> BitLength.of(2)
2
iex> BitLength.of(3)
2
iex> BitLength.of(255)
8
iex> BitLength.of(256)
9
"""
@doc """
Calculates the bit length of a non-negative integer.
The bit length is the minimum number of bits needed to represent the integer
in binary form. For example:
- 0 requires 0 bits (special case)
- 1 requires 1 bit (binary: 1)
- 2 requires 2 bits (binary: 10)
- 3 requires 2 bits (binary: 11)
- 255 requires 8 bits (binary: 11111111)
- 256 requires 9 bits (binary: 100000000)
## Parameters
- `integer` - A non-negative integer (>= 0)
## Returns
- `non_neg_integer()` - The number of bits required to represent the integer
## Examples
iex> BitLength.of(0)
0
iex> BitLength.of(1)
1
iex> BitLength.of(2)
2
iex> BitLength.of(3)
2
iex> BitLength.of(7)
3
iex> BitLength.of(8)
4
iex> BitLength.of(255)
8
iex> BitLength.of(256)
9
iex> BitLength.of(1023)
10
iex> BitLength.of(1024)
11
## Algorithm
The function uses the mathematical relationship between bit length and logarithms:
- For a positive integer n, the bit length is $\\lfloor \\log_2{n} \\rfloor + 1$
- For n = 0, the bit length is 0 (special case)
This is equivalent to finding the position of the most significant bit (MSB)
in the binary representation of the number.
## Performance
The function uses `:math.log2/1` which provides O(1) performance for
calculating the base-2 logarithm of the input integer.
"""
@spec of(non_neg_integer()) :: non_neg_integer()
def of(integer)
def of(0), do: 0
def of(n) when n > 0 do
n
|> :math.log2()
|> Float.floor()
|> trunc()
|> Kernel.+(1)
end
end