Skip to content

Instantly share code, notes, and snippets.

@havenwood
Forked from Nurdok/python_conversion.md
Last active June 6, 2018 19:33
Show Gist options
  • Save havenwood/5426260 to your computer and use it in GitHub Desktop.
Save havenwood/5426260 to your computer and use it in GitHub Desktop.

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!

@jacobian
Copy link

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

@havenwood
Copy link
Author

@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