本文介绍了如何在 Ruby 中将字符串或整数转换为二进制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将整数 0..9 和数学运算符 + - */in 创建为二进制字符串.例如:
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?
推荐答案您可以使用 Integer#to_s(base) 和 String#to_i(base).
Integer#to_s(base) 将十进制数转换为表示指定基数的字符串:
Integer#to_s(base) converts a decimal number to a string representing the number in the base specified:
9.to_s(2) #=> "1001"而使用 String#to_i(base) 获得相反的结果:
while the reverse is obtained with String#to_i(base):
"1001".to_i(2) #=> 9更多推荐
如何在 Ruby 中将字符串或整数转换为二进制?
发布评论