# Convert Decimal to Any Base

Page 1 of 1

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

### #1 erik.price

• D.I.C Lover

Reputation: 486
• 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

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

 .related ul { list-style-type: circle; font-size: 12px; font-weight: bold; } .related li { margin-bottom: 5px; background-position: left 7px !important; margin-left: -35px; } .related h2 { font-size: 18px; font-weight: bold; } .related a { color: blue; }