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

后端 未结 8 1388
栀梦
栀梦 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:46

    You would naturally use Integer#to_s(2), String#to_i(2) or "%b" in a real program, but, if you're interested in how the translation works, this method calculates the binary representation of a given integer using basic operators:

    def int_to_binary(x)
      p = 0
      two_p = 0
      output = ""
    
      while two_p * 2 <= x do
        two_p = 2 ** p
        output << ((two_p & x == two_p) ? "1" : "0")
        p += 1
      end
    
      #Reverse output to match the endianness of %b
      output.reverse
    end
    

    To check it works:

    1.upto(1000) do |n|
      built_in, custom = ("%b" % n), int_to_binary(n)
      if built_in != custom
        puts "I expected #{built_in} but got #{custom}!"
        exit 1
      end
      puts custom
    end
    

提交回复
热议问题