This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Converting Hex to decimal - with a twist Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Converting Hex to decimal - with a twist" Watch "Converting Hex to decimal - with a twist" New topic
Author

Converting Hex to decimal - with a twist

Toby Freeman
Greenhorn

Joined: Jul 18, 2003
Posts: 2
Hi All

I'm having a bit of an issue trying to convert a String hexidecimal value to a decimal.

The data I'm receiving are cartesian coordinates (X,Y,Z) as Strings in a hexadecimal format of a fixed length i.e. "003df860".

Normally, I would just use the following code:



to return my answer. This works fine for positive coordinates.

However, cartesian coordinates can be also be negative, so with a value such as "FFFB6825", I want parseInt to return -301019, not a NumberFormatException as the the number is too large (4294666270).

Anyone got any suggestions as to how I can get round this?

Is it one of those things that is staring at me right under my nose?

Thanks

Toby
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
I'm thinking if it starts with F then XOR the string, do the parserInt() bit, flip the sign and subtract 1.

XOR the string is interesting ... gotta translate F=0 E=1, D=2 ... 0=F. This is real ugly but seems to work:


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Dirk Schreckmann
Sheriff

Joined: Dec 10, 2001
Posts: 7023
You might prefer to simple first make a long, then cast the value to int.


[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
Dirk Schreckmann
Sheriff

Joined: Dec 10, 2001
Posts: 7023
Oh, and...

Welcome to JavaRanch, Toby Freeman!
Toby Freeman
Greenhorn

Joined: Jul 18, 2003
Posts: 2
Dirk - fantastic thank you.

I'm coming here again if I keep getting answers so quick...

Toby
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Ah, does that cast to int convert from a very large positive long to a negative int? I tried long and saw the wrong number but never tried casting it back.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Converting Hex to decimal - with a twist
 
Similar Threads
custom Layout Managers
Struts2, How to populate this object with json
2D Polygon shapes
Decimals not converting to correct fractions
Math help