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

后端 未结 8 1360
栀梦
栀梦 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
    
    0 讨论(0)
  • 2020-11-30 18:08

    Picking up on bta's lookup table idea, you can create the lookup table with a block. Values get generated when they are first accessed and stored for later:

    >> lookup_table = Hash.new { |h, i| h[i] = i.to_s(2) }
    => {}
    >> lookup_table[1]
    => "1"
    >> lookup_table[2]
    => "10"
    >> lookup_table[20]
    => "10100"
    >> lookup_table[200]
    => "11001000"
    >> lookup_table
    => {1=>"1", 200=>"11001000", 2=>"10", 20=>"10100"}
    
    0 讨论(0)
提交回复
热议问题