将整数转换为二进制字符串,用前导零填充

时间:2013-07-03 07:51:19

标签: ruby-on-rails ruby

我想创建新方法Integer#to_bin,将十进制转换为二进制字符串。 #to_bin的参数是位数。结果应该用前导零填充,以使其具有多个数字。

示例:

1.to_bin(4)
#=> "0001"
1.to_bin(3)
#=> "001"
1.to_bin(2)
#=> "01"
7.to_bin(1)
#=> nil
7.to_bin
#=> "111"
etс.

我尝试了什么:

class Integer

    def to_bin(number=nil)
        if number == nil
          return self.to_s(2)
        else 
          s = self.to_s(2).size
          e = number-s
          one = '0'
          two = '00'
          three = '000'

        if e==one.size
          one+self.to_s(2)
        elsif e==two.size
          two+self.to_s(2)
        elsif e==three.size
          three+self.to_s(2)
        end
        end
    end
end

如何将整数转换为以前导零填充的二进制字符串?

2 个答案:

答案 0 :(得分:25)

执行此操作的适当方法是使用内核的sprintf格式:

'%03b' % 1 # => "001"
'%03b' % 2 # => "010"
'%03b' % 7 # => "111"

'%08b' % 1 # => "00000001"
'%08b' % 2 # => "00000010"
'%08b' % 7 # => "00000111"

但等等,还有更多!:

'%0*b' % [3, 1] # => "001"
'%0*b' % [3, 2] # => "010"
'%0*b' % [3, 7] # => "111"

'%0*b' % [8, 1] # => "00000001"
'%0*b' % [8, 2] # => "00000010"
'%0*b' % [8, 7] # => "00000111"

因此,定义一个扩展Fixnum或Integer的方法很简单,干净利落:

class Integer
  def to_bin(width)
    '%0*b' % [width, self]
  end
end

1.to_bin(8) # => "00000001"
0x55.to_bin(8) # => "01010101"
0xaaa.to_bin(16) # => "0000101010101010"

答案 1 :(得分:10)

Ruby已经有一个将数字转换为二进制的内置机制:#to_s接受转换为的基数。

30.to_s(2) # => "11110"

如果你想用零填充它:

30.to_s(2).rjust(10, "0") => "0000011110"

你可以将它扩展为一个结合了两者的小方法:

class Fixnum
  def to_bin(width = 1)
    to_s(2).rjust(width, "0")
  end
end

> 1234.to_bin
=> "10011010010"
> 1234.to_bin(20)
=> "00000000010011010010"