5

I know that I can use Fixnum#to_s to represent integers as strings in binary format. However 1.to_s(2) produces 1 and I want it to produce 00000001. How can I make all the returned strings have zeros as a fill up to the 8 character? I could use something like:

binary = "#{'0' * (8 - (1.to_s(2)).size)}#{1.to_s(2)}" if (1.to_s(2)).size < 8

but that doesn't seem very elegant.

4

3 回答 3

9

使用字符串格式。

"%08b" % 1
# => "00000001"
于 2013-11-08T07:23:44.617 回答
8

使用String#rjust

1.to_s(2).rjust(8, '0')
=> "00000001"
于 2013-11-08T07:28:21.710 回答
4

使用String#%方法格式化字符串

 "%08d" % 1.to_s(2)
 # => "00000001" 

这是不同格式选项的参考

于 2013-11-08T07:22:28.057 回答