如何在 Ruby 中将字符串或整数转换为二进制?

编程入门 行业动态 更新时间:2024-10-28 13:15:43
本文介绍了如何在 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 中将字符串或整数转换为二进制?

本文发布于:2023-06-05 01:22:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/508991.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   字符串   转换为   中将   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!