Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KINGSABRI/cfa9917d0a52e985ea1c85d45d8ba165 to your computer and use it in GitHub Desktop.
Save KINGSABRI/cfa9917d0a52e985ea1c85d45d8ba165 to your computer and use it in GitHub Desktop.
ruby converting an unsigned int to hexadecimal (java-like implementation)
# In Java, the following expression
# Integer.toHexString(1286933134)
# produces:
# "4cb50a8e"
# and
# Integer.toHexString(-1286933134)
# produces:
# "b34af572"
# ref doc: http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toHexString(int)
# In Ruby, to acheive same results:
# for positive number:
(1286933134).to_s(16)
# produces:
# "4cb50a8e" which matches with the Java's,
# but if the number is negative:
(-1286933134).to_s(16)
# then the result is not what we expect:
# "-4cb50a8e"
# so, to acheive same result for negative
# numbers too, we've to mod that number
# by 2^32 (i.e. in terms of Ruby: 2**32):
(-1286933134 % 2**32).to_s(16)
# and the result is similar as of Java's:
# "b34af572"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment