Converting Hex in Java, wrong value with negative values
<p>I have seen several questions on the topic mentioned in the subject (e.g <a href="https://stackoverflow.com/questions/12005424/java-converting-int-to-hex-and-back-again">this one</a>), but it seems to me that none of them provided this example. I'm using Java7 and I want to convert a <code>String</code> representing an hexadecimal or a decimal into an <code>Integer</code> or <code>Long</code> value (depends on what it represents) and I do the following:</p>

<pre><code>public Number getIntegerOrLong(String num) {
    try {
        return Integer.decode(num);
    } catch (NumberFormatException nf1) {
        final long decodedLong = Long.decode(num);
        if ((int) decodedLong == decodedLong) {//used in Java8 java.util.Math.toIntExact()
            return (int) decodedLong;
        }
        return decodedLong;
    }
}
</code></pre>

<p>When I use a String representing a decimal number everything is ok, the problem are arising with negative hexadecimals</p>

<p>Now, If I do:</p>

<pre><code>String hex = "0x"+Integer.toHexString(Integer.MIN_VALUE);
Object number = getIntegerOrLong(hex);
assertTrue(number instanceof Integer):
</code></pre>

<p>fails, because it returns a <code>Long</code>. Same for other negative integer values.</p>

<p>Moreover, when I use <code>Long.MIN_VALUE</code> like in the following:</p>

<pre><code>String hex = "0x"+Integer.toHexString(Long.MIN_VALUE);
Object number = getIntegerOrLong(hex);
assertTrue(number instanceof Long):
</code></pre>

<p>fails, because of <code>NumberFormatException</code> with message:</p>

<pre><code>java.lang.NumberFormatException: For input string: "8000000000000000"
</code></pre>

<p>I also tried with other random <code>Long</code> values (so within the Long.MIN_VALUE and Long.MAX_VALUE, and it fails as well when I have negative numbers. E.g.</p>

<p>the <code>String</code> with the hexadecimal <code>0xc0f1a47ba0c04d89</code> for the <code>Long</code> number <code>-4,543,669,698,155,229,815</code> returns:</p>

<pre><code>java.lang.NumberFormatException: For input string: "c0f1a47ba0c04d89"
</code></pre>

<p>How can I fix the script to obtain the desired behavior?</p>