Forked from vishaltelangre/java_ruby_unsigned_int_to_hex.rb
Created
March 29, 2016 16:40
-
-
Save KINGSABRI/cfa9917d0a52e985ea1c85d45d8ba165 to your computer and use it in GitHub Desktop.
ruby converting an unsigned int to hexadecimal (java-like implementation)
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
# 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