如何将字符串中字符的 ASCII 值打印为二进制数?

How to print the ASCII value of characters in a string as binary numbers?

我正在尝试通过不同的方法实现它,但它仍然给出错误,那么如何使用 .ord 来实现它,或者有任何其他方法可以实现它? 基本上我想获取字符串中每个字符的 ASCII 值,然后使用 .to_s(2) 将每个字符转换为二进制 这是我的代码↓

input = gets.chomp.split("").each { |s| s.ord.to_i }
puts input.to_s(2)

试试这个

gets.chomp.chars.each { |ch| puts ch.ord }

chars 方法是另一种方法 split("")

您可以使用 each_codepoint to iterate the string's codepoints and printf%b 将其格式化为二进制数。

'foo bar'.each_codepoint { |c| printf("%07b\n", c) }

输出:

1100110
1101111
1101111
0100000
1100010
1100001
1110010

07 前缀将 最小 宽度设置为 7,并用 0 填充缺失的位(有关格式化选项,请参阅 sprintf)。不过,可能会有超过 7 位的字符。