Created
July 14, 2011 14:01
-
-
Save pcarrier/1082509 to your computer and use it in GitHub Desktop.
Turn a number to bytes in Ruby
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 characters
| 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