Skip to content

Instantly share code, notes, and snippets.

@vishaltelangre
Created January 8, 2014 06:59
Show Gist options
  • Select an option

  • Save vishaltelangre/8312873 to your computer and use it in GitHub Desktop.

Select an option

Save vishaltelangre/8312873 to your computer and use it in GitHub Desktop.

Revisions

  1. vishaltelangre created this gist Jan 8, 2014.
    25 changes: 25 additions & 0 deletions java_ruby_unsigned_int_to_hex.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    # 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"