Skip to content

Instantly share code, notes, and snippets.

What would you like to do?

Ruby Number Conversion Chart

From To Expression
45 "45" data.to_s
45 "101101" data.to_s(2)
45 "2D" data.to_s(16)
45 "\x00\x00\x00\x2d" [data].pack("i>")
"45" 45 data.to_i
"45" "3435" data.unpack("H*")[0]
"101101" 45 data.to_i(2)
"2D" 45 data.hex
"2D" "\x2d" data.hex.chr
"\x00\x00\x00\x2d" 45 data.unpack("i>")[0]
"\x2d" "2D" data.ord.to_s(16)
"3435" "45" [data].pack("H*")

Ruby translation of the original Python gist. There is also a Scala gist translation.

Thanks to MrZYX, Hanmac, and jacobian for the pack and unpack solutions!


This comment has been minimized.

Copy link

@jacobian jacobian commented Apr 20, 2013

For converting to/from hex strings, you can also do: ["3435"].pack("H*") and "45".unpack("H*")[0].


This comment has been minimized.

Copy link
Owner Author

@havenwood havenwood commented Apr 21, 2013

@jacobian Awesome, thanks!! Swapped to your solution above. (Made the column way smaller, yay!)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.