# Hex conversion

## Recommended Posts

Does anybody know a trick to do quick hex conversion? I need to convert integer string (number taking up more space than 32 bits) to hex string?

##### Share on other sites
tok_junior    229
sprintf(hexString,"%X",atoi(decString));
should work.

##### Share on other sites
That would be fast and simple, but... atoi clamps number into 32bit integer, so you wont get more than 8 hex digits even if you should...

##### Share on other sites
tok_junior    229
Iterate through the string and convert 9 digits at a time. By doing 9, you can be sure you're not overflowing.
Another way would be by converting it yourself, preferably by making a conversion-table.

##### Share on other sites
Skizz    794
Doing it nine digits at a time will not work. 109 in hex is 0x3B9ACA00 which is not the same as treating it as two nine digit numbers (1 and 0).

If you want to be able to accurately convert numbers that exceed the standard number formats (64/32/etc. bit), then you need to create a set of functions / class to do this. Lucky for you, as a result of another thread, I've written a class to do this and it can be downloaded here. You'll need to write your own hex output routine, but that's really trivial - there's an example of base 10 output that can be changed to base 16, or you can delve into the inner structure and output each char in the stored number as a hex pair.

Skizz

P.S. I don't think there's a quick method for number base conversion other than the brute force approach.

##### Share on other sites
Trap    684
Gnu Bignums

Base conversion between bases which are no multiples of each other all work by dividing through the new base and collecting remainders.

In languages with builtin bignums like common lisp it would be a 1-liner.