Skip to content

Instantly share code, notes, and snippets.

@vishaltelangre
Created January 8, 2014 06:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save vishaltelangre/8312873 to your computer and use it in GitHub Desktop.
Save vishaltelangre/8312873 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