How to return a fixed length binary representation of an integer in Ruby?

泪湿孤枕 提交于 2019-12-21 05:03:15

问题


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.


回答1:


Use string format.

"%08b" % 1
# => "00000001"



回答2:


Using String#rjust:

1.to_s(2).rjust(8, '0')
=> "00000001"



回答3:


Use the String#% method to format a string

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

Here is a reference for different formatting options.



来源:https://stackoverflow.com/questions/19853566/how-to-return-a-fixed-length-binary-representation-of-an-integer-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!