• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

Converting Hex to decimal - with a twist  RSS feed

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You might prefer to simple first make a long, then cast the value to int.
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh, and...

Welcome to JavaRanch, Toby Freeman!
 
Toby Freeman
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dirk - fantastic thank you.

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

Toby
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!