Converter to binary
1
A simple algorithm to convert decimal numbers to binary; pointless since most languages have an inbuilt function but was used for learning about algorithm design.
#take decimal
#work out limits in binary
#find smallest power of 2 that is greater than number
#divide number by greatest column and carry remainder
#keep on dividing by subsequent columns
#if result<1 do nothing if result >1 carry remainder
#until result=1 when number finished
#remaining colums will be 0
#e.g 13
#4-bit
#13/8=1r5
#so check 8
#5/4=1r1
#so check 4
#1/2<1 so skip
#1/1 so check 1
#number finished at 1101
puts "Enter number to be converted to binary:"
number=gets.chomp.to_i
numberstore=number
#Define number of powers necessary:
iteration=1
while 2**iteration<number do
iteration+=1
end
#so max column = 2^iteration
maxcolumn=2**iteration
iteration=0
#Actual calc.
#localans is used to store the result of the division
output=Array.new
while maxcolumn>=1 do
localint=number/maxcolumn
localrem=number.remainder(maxcolumn)
if localint >= 1 then
output[iteration]=1
else
output[iteration]=0
end
iteration+=1
maxcolumn/=2
number=localrem
end
puts "#{numberstore} in binary is #{output.to_s}"
#TODO: Doesn't print in standard bit sizes i.e. 4=100 not 0100






There are currently no comments for this snippet.