如何返回在Ruby中的一个整数的固定长度的二进制重新presentation? [英] How to return a fixed length binary representation of an integer in Ruby?
本文介绍了如何返回在Ruby中的一个整数的固定长度的二进制重新presentation?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道,我可以使用#长整数to_s
重新present整数作为二进制格式的字符串。然而 1.to_s(2)
产生 1
,我希望它产生 00000001
。我怎样才能使所有返回的字符串具有零作为填充到8字符?我可以使用类似:
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.
推荐答案
使用字符串格式。
"%08b" % 1
# => "00000001"
这篇关于如何返回在Ruby中的一个整数的固定长度的二进制重新presentation?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文