如何在 Ruby 中将字符串或整数转换为二进制? [英] How to convert a string or integer to binary in Ruby?

查看:45
本文介绍了如何在 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 中将字符串或整数转换为二进制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆