To split a number into digits in a given base, Julia has the digits()
function:
julia> digits(36, base = 4)
3-element Array{Int64,1}:
0
1
2
What's the reverse operation? If you have an array of digits and the base, is there a built-in way to convert that to a number? I could print the array to a string and use parse()
, but that sounds inefficient, and also wouldn't work for bases > 10.
The answer seems to be written directly within the documentation of
digits
:So for your case this will work:
And the above code can be shortened with the dot operator:
The previous answers are correct, but there is also the matter of efficiency:
collects the numbers into an array before summing, which causes unnecessary allocations. Skip the brackets to get better performance:
This also allocates an array before summing:
sum(d.*4 .^(0:(length(d)-1)))
If you really want good performance, though, write a loop and avoid repeated exponentiation:
This has one extra unnecessary multiplication, you could try to figure out some way of skipping that. But the performance is 10-15x better than the other approaches in my tests, and has zero allocations.
Edit: There's actually a slight risk to the type handling above. If the input vector and
base
have different integer types, you can get a type instability. This code should behave better: