Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of `int.bit_length()` in Julia

Tags:

int

julia

What is the equivalent of Python's int.bit_length() in Julia?

int.bit_length(): Return the number of bits necessary to represent an integer in binary, excluding the sign and leading zeros

like image 584
norok2 Avatar asked Oct 07 '19 19:10

norok2


Video Answer


1 Answers

In Julia there is the ndigits function.

ndigits(n::Integer; base::Integer=10, pad::Integer=1)

Compute the number of digits in integer n written in base base (base must not be in [-1, 0, 1]), optionally padded with zeros to a specified size (the result will never be less than pad).

Examples

julia> ndigits(12345)
5

julia> ndigits(1022, base=16)
3

julia> string(1022, base=16)
"3fe"

julia> ndigits(123, pad=5)
5

You want to use it with the base = 2 keyword argument:

julia> ndigits(32, base = 2)
6
like image 64
giordano Avatar answered Oct 09 '22 15:10

giordano