Precautions when converting from decimal number to binary number

Introduction

I am a beginner in programming. I will write an article for the first time this time. In order to make it a habit to output in the future, I would like to write gradually from the shortest one, which also serves as practice.

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

Precautions when converting

When converting from decimal number to n-ary number and from n-ary number to decimal number, the method used changes.

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

By passing an argument to the to_s method, each character string from 2 to 36 bases is returned.

p 255.to_s(2)    # => "11111111"Decimal number → binary number
p 255.to_s(8)    # => "377"Decimal number → 8 decimal number
p 255.to_s(16)   # => "ff"Decimal number → hexadecimal number
p 255.to_s(32)   # => "7v"Decimal number → 32 base number
p 255.to_s(36)   # => "73"Decimal number → 36-ary number

Use the to_i method to convert an n-ary number to a decimal number

If you want to convert an n-ary number to a decimal number in the reverse of the above, pass an argument to the to_i method.

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

Finally

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

Recommended Posts

Precautions when converting from decimal number to binary number
Precautions when migrating from VB6.0 to JAVA
[Java] Tips and error issues when converting from double to Big Decimal
Converting from decimal to binary is too difficult to do without long division! !!
Story when moving from Spring Boot 1.5 to 2.1
Changes when migrating from Spring Boot 1.5 to Spring Boot 2.0
Changes when migrating from Spring Boot 2.0 to Spring Boot 2.2
Troubleshooting when raising Mastodon from v3.0.x to v3.1.x
[JSR-310 Date and Time API] Precautions for format definition when converting from Japanese calendar character string to date type
Summary of good points and precautions when converting Java Android application to Kotlin
Summary of moss when updating from JMockit 1.4 to 1.30
What do you use when converting to String?
Jet lag countermeasures when going from Japan to JavaOne