Skip to content

Instantly share code, notes, and snippets.

@jcasimir
Last active July 29, 2024 15:41
Show Gist options
  • Save jcasimir/825d7b2cf62bc19e6f9a4854a1bd51cb to your computer and use it in GitHub Desktop.
Save jcasimir/825d7b2cf62bc19e6f9a4854a1bd51cb to your computer and use it in GitHub Desktop.
  • On your own, can you write a bit of code that prompts the user for a base-10 quantity then outputs it in binary, octal, and hex?

  • Example:

    Quantity (base-10): 29
    
    base-2:  11101
    base-8:  35
    base-16: 1D
    
  • Rules: Don’t use any built-in conversion available in your langugage of choice — that would be a little too easy, no? Try and figure out the mathematic approach. If you write tests it’s legit to use the built-in conversion in your test cases.

  • Hint: You’re likely going to need the modulo operator, %, which outputs the remainder of division.

  • Second hint: Build this iteratively — try to get just one conversion figured out before starting a second one.

class Converter
def self.to_b(dec)
modulus = dec % 2
dividend = dec / 2
if dividend == 0
return modulus.to_s
else
return to_b(dividend) + modulus.to_s
end
end
def self.to_o(dec)
modulus = dec % 8
dividend = dec / 8
if dividend == 0
return modulus.to_s
else
return to_o(dividend) + modulus.to_s
end
end
def self.to_h(dec)
modulus = dec % 16
dividend = dec / 16
if dividend == 0
return hex_lookup(modulus)
else
return to_h(dividend) + hex_lookup(modulus)
end
end
def self.hex_lookup(decimal)
[
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
"A", "B", "C", "D", "E", "F"
][decimal]
end
end
require 'minitest'
require 'minitest/autorun'
require './converter'
class ConverterTest < Minitest::Test
def test_it_converts_single_digits_to_binary
assert_equal "1", Converter.to_b(1)
assert_equal "10", Converter.to_b(2)
assert_equal "11", Converter.to_b(3)
assert_equal "1000", Converter.to_b(8)
assert_equal "1001", Converter.to_b(9)
end
def test_it_converts_single_digits_to_octal
assert_equal "2", Converter.to_o(2)
assert_equal "3", Converter.to_o(3)
assert_equal "10", Converter.to_o(8)
assert_equal "11", Converter.to_o(9)
end
def test_it_converts_to_hex
assert_equal "2", Converter.to_h(2)
assert_equal "F", Converter.to_h(15)
assert_equal "10", Converter.to_h(16)
assert_equal "11", Converter.to_h(17)
assert_equal "FF", Converter.to_h(255)
end
end
require './converter'
print "Quantity (base-10): "
input = gets.chomp.to_i
output = "
base-2: #{Converter.to_b(input)}
base-8: #{Converter.to_o(input)}
base-16: #{Converter.to_h(input)}
"
puts output
@jcasimir
Copy link
Author

Ummm... sorry. The input in the example was supposed to be 29!!!

@jcasimir
Copy link
Author

(Since the binary ends in 1 the input must have been an odd number!)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment