Skip to content

Instantly share code, notes, and snippets.

@whitehat101
Last active August 31, 2016 01:29
Show Gist options
  • Save whitehat101/c532035f72b29deab3418cdcaca91f53 to your computer and use it in GitHub Desktop.
Save whitehat101/c532035f72b29deab3418cdcaca91f53 to your computer and use it in GitHub Desktop.
Base N to Base M conversions (using Numeric arrays, not an extended alphabet)
"""
Port the to_base/from_base functions from Ruby to Python
"""
from __future__ import division
def __to_base_notation(value, base):
result = []
while value > 0 or not len(result):
part = value % base
value = (value - part) / base
result.append(part)
result.reverse()
return result
__to_base_notation(152, 10)
def __from_base_notation(parts, base):
value = 0
for exponent, digit in enumerate(reversed(parts)):
value += digit * (base ** exponent)
return value
__from_base_notation([1,5,2], 10)
# Convert from any base to any base using arrays of Numerics (not an extended alphabet)
# Only positive values considered.
#
# [1,5,2].from_base 10 => 152
# 152.to_base 10 => [1,5,2]
#
# Don't forget that Ruby handles bases 1..36 nativly (with an extended alphabet) with to_s and to_i:
# 0b01010100.to_s 16 #=> "54"
# 0xc8.to_s 2 #=> "11001000"
# "10111001".to_i(2).to_s(16) #=> "b9"
#
# For a gem like this, but allows setting custom extended alphabets:
# https://github.com/rubyworks/radix
class Array
def from_base base
self.reverse.each.with_index.inject 0 do |value,(digit,exponent)|
value + digit * (base ** exponent)
end
end
end
class Numeric
def to_base base
value = self.abs
result = []
begin
part = value % base
value = (value - part) / base
result << part
end while value > 0
result.reverse
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment