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.
When converting from decimal number to n-ary number and from n-ary number to decimal number, the method used changes.
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
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
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.