Elixir: How to get bit_size of an Integer variable?

587 Views Asked by At

I need to get the size of bits used in one Integer variable.

like this:

bit_number = 1
bit_number = bit_number <<< 2
bit_size(bit_number)   # must return 3 here

the bit_size/1 function is for 'strings', not for integers but, in the exercise, whe need to get the size of bits of the integer.

I'm doing one exercise of compression of an book (Classic Computer Science Problems in Python, of Daivid Kopec) and I'm trying to do in Elixir for study.

3

There are 3 best solutions below

0
On BEST ANSWER

This works:

(iex) import Bitwise
(iex) Integer.digits(1 <<< 1, 2) |> length
2

but I'm sure there are better solutions.

(as @Hauleth mentions, the answer here should be 2, not 3)

0
On

You can count how many times you can divide it by two:

defmodule Example do
  def bits_required(0), do: 1
  def bits_required(int), do: bits_required(int, 1)
  defp bits_required(1, acc), do: acc
  defp bits_required(int, acc), do: bits_required(div(int, 2), acc + 1)
end

Output:

iex> Example.bits_required(4)
3
0
On

The easiest (and technically most flexible) option is to use the fact that n will have exactly ceil(log_b(n)) digits in base b. So what we are looking for is:

ceil(:math.log2(n))