How to convert a string or integer to binary in Ruby?

后端 未结 8 1400
栀梦
栀梦 2020-11-30 17:22

How do you create integers 0..9 and math operators + - * / in to binary strings. For example:

 0 = 0000,
 1 = 0001, 
 ...
 9 = 1001

Is the

8条回答
  •  我在风中等你
    2020-11-30 18:07

    You have Integer#to_s(base) and String#to_i(base) available to you.

    Integer#to_s(base) converts a decimal number to a string representing the number in the base specified:

    9.to_s(2) #=> "1001"
    

    while the reverse is obtained with String#to_i(base):

    "1001".to_i(2) #=> 9
    

提交回复
热议问题