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

后端 未结 8 1391
栀梦
栀梦 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 17:44

    I am almost a decade late but if someone still come here and want to find the code without using inbuilt function like to_S then I might be helpful.

    find the binary

    def find_binary(number)
      binary = []  
      until(number == 0)
        binary << number%2
        number = number/2
      end
      puts binary.reverse.join
    end
    

提交回复
热议问题