binaryelixirbitwise-operatorselixir-iex

Elixir: How to get bit_size of an Integer variable?


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.


Solution

  • 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)