Skip to content

Instantly share code, notes, and snippets.

@grobie
Created October 30, 2008 09:32
Show Gist options
  • Save grobie/20949 to your computer and use it in GitHub Desktop.
Save grobie/20949 to your computer and use it in GitHub Desktop.
class Integer
def to_base(base)
number = self.abs
result = ''
digits = (0..9).to_a + ('A'..'Z').to_a
raise "Sorry, there aren't enough characters to convert #{number} to base #{base}" if base > digits.size
while number > 0
result = digits[number % base].to_s + result
number = number / base
end
self<0 ? "-#{result}" : result
end
def to_twos_complement(bitsize = 16)
self < 0 ? (self + 2**bitsize).to_base(2) : to_base(2).rjust(bitsize, '0')
end
end
puts "c)\n\n"
for base in [2,8,16,13]
puts "Umrechnung zur Basis #{base}"
for number in [93, 10000, 32768, 314171, 1048576]
puts "Die Zahl #{number} ergibt zur Basis #{base}: #{number.to_base(base)}"
end
puts "\n"
end
puts "d)\n\n"
for number in [-1, 1, 57, -84, -256, 257]
puts "Die Zahl #{number} ergibt in Zweierkomplementdarstellen: #{number.to_twos_complement}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment