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

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

    If you're only working with the single digits 0-9, it's likely faster to build a lookup table so you don't have to call the conversion functions every time.

    lookup_table = Hash.new
    (0..9).each {|x|
        lookup_table[x] = x.to_s(2)
        lookup_table[x.to_s] = x.to_s(2)
    }
    lookup_table[5]
    => "101"
    lookup_table["8"]
    => "1000"
    

    Indexing into this hash table using either the integer or string representation of a number will yield its binary representation as a string.

    If you require the binary strings to be a certain number of digits long (keep leading zeroes), then change x.to_s(2) to sprintf "%04b", x (where 4 is the minimum number of digits to use).

提交回复
热议问题