BitLength

Hex.pm Hex.pm Hex.pm

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

What is Bit Length?

The bit length of an integer is the minimum number of bits required to represent that integer in binary form, excluding leading zeros. 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)

Installation

The package can be installed by adding bit_length to your list of dependencies in mix.exs:

def deps do
  [
    {:bit_length, "~> 1.0"}
  ]
end

Usage

# Calculate bit length of various integers
BitLength.of(0)    # Returns: 0
BitLength.of(1)    # Returns: 1
BitLength.of(2)    # Returns: 2
BitLength.of(3)    # Returns: 2
BitLength.of(7)    # Returns: 3
BitLength.of(8)    # Returns: 4
BitLength.of(255)  # Returns: 8
BitLength.of(256)  # Returns: 9
BitLength.of(1023) # Returns: 10
BitLength.of(1024) # Returns: 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.

Documentation

Documentation is available on HexDocs.

License

Copyright (c) 2025 University of Kitakyushu

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Changelog

See CHANGELOG.md for a list of changes and version history.