Skip to content

Instantly share code, notes, and snippets.

@xfbs
Created March 15, 2013 13:39
Show Gist options
  • Save xfbs/5169921 to your computer and use it in GitHub Desktop.
Save xfbs/5169921 to your computer and use it in GitHub Desktop.
Ruby: convert string to binary form and back (one liners
# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment