0 Replies - 1233 Views - Last Post: 28 December 2009 - 05:33 PM

#1 erik.price   User is offline

  • D.I.C Lover
  • member icon

Reputation: 486
  • View blog
  • Posts: 2,690
  • Joined: 18-December 08

Convert Decimal to Any Base

Posted 28 December 2009 - 05:33 PM

Description: Converts a given decimal to a random base. Initially allows only up to base 64, but you can add any other symbols you want to allow you to convert to any higher base you want.
def toBaseN(dec, base)
  
  nums ='0123456789ABCDEFGHI'
            'JKLMNOPQRSTUVWXYZab'
            'cdefghijklmnopqrstuvwxyz+/'
   #allows up to base 64
   #add your own symbols to allow you to use higher bases
   
   result = ""
   #result string
   
   return nil if dec.instance_of? Float
   #if anyone has any idea how to make floating points acceptable, I'd love to hear it!
   
   return nil if base < 2
   #base 0 isn't possible, and neither is base 1
   
   return 0 if dec == 0
   #0 is 0 in every base
   
   while dec != 0
     
     result += nums[dec%base].chr
     
     dec /= base
     
   end
   
   return result.reverse    
   
 end

#example usage: 
puts toBaseN(2,2)    #=>10
puts toBaseN(128,64) #=>20


Is This A Good Question/Topic? 0
  • +

Page 1 of 1