-
-
Save v9n/d83cc23c06394efffec062239b54b0ee to your computer and use it in GitHub Desktop.
Revisions
-
xfbs created this gist
Mar 15, 2013 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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