Tobi Alafin Tobi Alafin - 1 year ago 72
Ruby Question

How do I Improve this code

This is the original code.

def d_to_b(dec, bin="")
dec = dec.to_i
if (dec < 2)
bin += dec.to_s
bin = bin.reverse
return bin
a = dec%2
bin += a.to_s
d_to_b(dec/2, bin)

def b_to_d(bin)
bin = bin.to_s
a = (bin.length - 1)
dec = 0
i = 0
while(i <= a)
dec += (bin[i].to_i)*(2**(a-i))
i += 1
return dec

I want to improve the code. make it faster, and shorten it. Any help, perhaps a more efficient algorithm.

Answer Source

Ruby has built in methods to do base conversions. Fixnum#to_s will take a base to convert to, and String#to_i will take a base to convert from.

$ ruby -e 'puts 12.to_s(2); puts "1100".to_i(2)'

Ruby does this work in C, you're not going to do it faster.

If you want to see how Ruby does it, have a look at rb_fix2str() and rb_cstr_parse_inum(). They're not simple.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download