Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 62 / 68

Converting Number Bases (Binary, Hex)

In this lesson you will learn how to convert numbers to binary and hexadecimal in Ruby and understand the basic idea of base conversion. This is for anyone searching for "Ruby base conversion to_s".

to_s(base) converts a number into a string in the base you specify. Going the other way, to_i(base) turns a string in that base back into a decimal number. Inside the computer, numbers are handled in exactly these bases.

The sample code converts 42 into a binary string with num.to_s(2) and into a hexadecimal string with num.to_s(16). Going back, "101010".to_i(2) returns the decimal 42, confirming the round trip.

A common stumbling block for beginners is the difference between plain to_s/to_i and the versions with a base. Omit the argument and you get the usual decimal form; supply one and the meaning changes completely.

Binary is used inside the computer and hexadecimal in colour codes, making this worthwhile background knowledge. For octal, just change the base argument of the same to_s call.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)