-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Closed
Description
Int#digits converts a non-negative number to an array of digits in a given base:
1234.digits # => [4, 3, 2, 1]
0xabc.digits(16) # => [12, 11, 10]There could be a constructor that does the opposite:
struct Int
def self.from_digits(digits : Enumerable(Int), base : Int = 10) : self
end
end
Int32.from_digits([4, 3, 2, 1]) # => 1234
UInt64.from_digits([12, 11, 10], 16) # => 0xabc_u64All digits must be within 0...base, and base must not be less than 2.
If digits.is_a?(Bytes) && base == 256, then this is more or less equivalent to IO::ByteFormat::LittleEndian#decode, except the digit count need not be the same as the the integer size. This method can also generalize BigInt#to_i and #9299 (but not #10101).
This method is called Integer.undigits/2 in Elixir. Note that Elixir uses the opposite digit order compared to Crystal and Ruby (whereas we append the digits from least to most significant to an Array, in Elixir prepending to linked lists is faster).
Sija