Skip to content

Instantly share code, notes, and snippets.

@v9n
Forked from xfbs/binary.rb
Created January 1, 2023 03:01
Show Gist options
  • Save v9n/d83cc23c06394efffec062239b54b0ee to your computer and use it in GitHub Desktop.
Save v9n/d83cc23c06394efffec062239b54b0ee to your computer and use it in GitHub Desktop.

Revisions

  1. @xfbs xfbs created this gist Mar 15, 2013.
    29 changes: 29 additions & 0 deletions binary.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,29 @@
    # not the most efficient way,
    # but you get the idea.

    str = "meow"

    # convert string to binary
    bin = str.bytes.map{|d| d.to_s(2)}.map{|b| b.rjust(8, '0')}.join
    puts bin

    # and convert it back to a string
    str = bin.scan(/.{8}/).map{|m| m.to_i(2)}.map{|n| n.chr}.join
    puts str

    # and here come the explanations
    bin = str.
    bytes. # split the string into it's bytes
    map{|d| # iterate over the bytes
    d.to_s(2)}. # turn each into string in base 2
    map{|b| # iterate over the strings
    b.rjust(8, '0')}. # pad each to be 8 characters wide (fill with zeros on right side)
    join # piece them together as string

    str = bin.
    scan(/.{8}/). # split the string into groups of 8 characters (.{8} matches 8 characters)
    map{|m| # iterate over the groups
    m.to_i(2)}. # turn each to an int, interpreting it to be in base 2
    map{|n| # for each int
    n.chr}. # turn it into a character
    join # join the resulting characters into a string