Skip to content

Instantly share code, notes, and snippets.

@pcarrier
Created July 14, 2011 14:01
Show Gist options
  • Save pcarrier/1082509 to your computer and use it in GitHub Desktop.
Save pcarrier/1082509 to your computer and use it in GitHub Desktop.
Turn a number to bytes in Ruby
class Numeric
def to_bytes
f = self
1.upto((Math.log2(self)/8).ceil).collect do
f, c = f.divmod 256; c
end.reverse
end
end
if __FILE__ == $PROGRAM_NAME and ARGV.length > 0
p ARGV[0].hex.to_bytes.pack("c*")
end
# ruby bytes_demo.rb 0x7075626c696320646f6d61696e #=> "public domain"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment