Skip to content

Instantly share code, notes, and snippets.

@arthurchui
Created March 17, 2016 22:46
Show Gist options
  • Save arthurchui/92e356a4ace258ab1dc9 to your computer and use it in GitHub Desktop.
Save arthurchui/92e356a4ace258ab1dc9 to your computer and use it in GitHub Desktop.
Get negative-base number from an integer
# Returns an array which index [0] represents the least significant bit.
# to_negativebase(9) # => [1, 0, 0, 1, 1]
# to_negativebase(-9) # => [1, 1, 0, 1]
def to_negativebase(value, base = -2)
raise ArgumentError if base > -2
digits = []
while value != 0
value, mod = value.divmod(base)
if mod < 0
mod += -base
value += 1
end
digits << mod
end
digits
end
# Converts a r-based number to an integer.
# The array[0] represents the least significant bit.
def to_int(a, base = -2)
a.each_with_index.inject(0) { |result, (n, i)| result + n * (base ** i) }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment