代码之家  ›  专栏  ›  技术社区  ›  user8269563

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

  •  0
  • user8269563  · 技术社区  · 7 年前

    .作战需求文件 基本上我想得到字符串中每个字符的ASCII值,然后使用 .to_s(2)

    input = gets.chomp.split("").each { |s| s.ord.to_i }
    puts input.to_s(2)
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   Ursus    7 年前

    试试这个

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

    chars split("")

        2
  •  1
  •   Stefan    7 年前

    您可以使用 each_codepoint 迭代字符串的代码点,并 printf %b 将其格式化为二进制数。

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

    1100110
    1101111
    1101111
    0100000
    1100010
    1100001
    1110010
    

    这个 07 前缀设置 宽度为7,焊盘缺失位 0 sprintf 格式选项)。不过,可能有超过7位的字符。