如何将字符串或整数转换为二进制在Ruby中? [英] How to convert a string or integer to binary in Ruby?
本文介绍了如何将字符串或整数转换为二进制在Ruby中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你如何创建+ 0..9整数和数学运算符 - * /中二进制字符串。
例如:
How do you create integers 0..9 and math operators + - * / in to binary strings. For example:
0 = 0000,
1 = 0001,
...
9 = 1001
有没有办法使用Ruby 1.8.6要做到这一点,而无需使用库?
Is there a way to do this with Ruby 1.8.6 without using a library?
推荐答案
您有整数#to_s(基地)
和 String.to_i(基地)
提供给你。
整数#to_s(基地)
转换为十进制数为字符串重新presenting在指定的基数量:
Integer#to_s(base)
converts a decimal number to a string representing the number in the base specified:
9.to_s(2) #=> "1001"
而与字符串#to_i(基地)中获得的反
:
"1001".to_i(2) #=> 9
这篇关于如何将字符串或整数转换为二进制在Ruby中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文