3

我想创建将十进制转换为二进制字符串的新方法 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

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

4

2 回答 2

33

执行此操作的适当方法是使用内核的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"
于 2013-07-03T08:16:32.283 回答
16

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"
于 2013-07-03T08:00:01.390 回答