Section 5.19. Finding Cube Roots, Fourth Roots, and so on


5.18. Performing Base Conversions

Obviously all integers are representable in any base, because they are all stored internally in binary. Further, we know that Ruby can deal with integer constants in any of the four commonly used bases. This means that if we are concerned about base conversions, we must be concerned with strings in some fashion.

If you are concerned with converting a string to an integer, that is covered in section 2.24, "Converting Strings to Numbers (Decimal and Otherwise)."

If you are concerned with converting numbers to strings, the simplest way is to use the to_s method with the optional base parameter. This naturally defaults to 10, but it does handle bases up to 36 (using all letters of the alphabet).

237.to_s(2)            # "11101101" 237.to_s(5)            # "1422" 237.to_s(8)            # "355" 237.to_s               # "237" 237.to_s(16)           # "ed" 237.to_s(30)           # "7r"


Another way is to use the % method of the String class:

hex = "%x" % 1234      # "4d2" oct = "%o" % 1234      # "2322" bin = "%b" % 1234      # "10011010010"


The sprintf method also works:

str = sprintf(str,"Nietzsche is %x\n",57005) # str is now: "Nietzsche is dead\n"


Obviously, printf will also suffice if you want to print out the value as you convert it.




The Ruby Way(c) Solutions and Techniques in Ruby Programming
The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)
ISBN: 0672328844
EAN: 2147483647
Year: 2004
Pages: 269
Authors: Hal Fulton

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net