Hi,
I´m having issues with making my converter spit out "signed" hex results.
decfield.setText(String.valueOf(Long.valueOf(hexfield.getText(), 16).longValue()));
What I get:
Hex (FFFFFFFF) -> Dec (4294967295)
What I wanted:
Hex (FFFFFFFF) -> Dec (-1)
Let me know what I have to modify in the code ^ above, please.
Thanks :smileyface:
First off, I'm guessing you want to use signed 32-bit correct? If so, you'll probably want to use int instead of long. As a result, you would use the Integer class and the parseInt(String s, int radix) method. However, according to this StackOverflow post (http://stackoverflow.com/questions/1410168/how-to-parse-negative-long-in-hex-in-java?rq=1), that method does not handle two's complement. Instead (using the answer from that page), you would want to use the BigInteger class. Your code would look something like this:
int x = new BigInteger(hexfield.getText(), 16).intValue();
decfield.setText(x+"");
You can, of course, stick this in a one liner like in your original code snippet if you so choose. Hope this helps.
Works perfectly.