[Ruby] Precautions when converting from decimal to binary

1 minute read


I am a beginner in programming. This is my first time writing an article. In order to make it a habit to output, I will gradually write from the short ones as well as practice.

This time, I was a little confused while studying at a certain skill check site, so I will also write my memorandum.

Notes on conversion

The method to use is different when converting from a decimal number to n-decimal number, and from n-decimal number to decimal number respectively.

To convert decimal number to n-ary number, use to_s method

By passing an argument to the to_s method, it returns a string of 2 to 36 decimal numbers.

p 255.to_s(2) # => "11111111" Decimal number → Binary number
p 255.to_s(8) # => "377" decimal → octal
p 255.to_s(16) # => "ff" Decimal number → Hexadecimal number
p 255.to_s(32) # => "7v" Decimal number → 32 decimal number
p 255.to_s(36) # => "73" decimal → 36 decimal

To convert n-base to decimal, use to_i method

If you want to convert n-decimal numbers to decimal numbers by the reverse of the previous procedure, pass an argument to the to_i method.

p "111000".to_i(2) # => 56 binary number → decimal number
p "111888".to_i(8) # => 73 octal number → decimal number
p "111fff".to_i(16)# => 1122303 Hexadecimal → Decimal
p "111vvv".to_i(32)# => 34668543 3 binary number → decimal number
p "111zzz".to_i(36)# => 62239103 36 decimal → decimal


It will be little by little in the future, but I would be happy if I could write an article and output it to help beginners like me. If you have any mistakes, please do not hesitate to point them out. Thank you for your cooperation.