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.
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)
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.