Skip to main content
gamedev.net
🔒 Locked

Hex conversion

Started by _Madman_ 4 replies 750+ views
Original Post
_Madman_
_Madman_
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?
______Madman
tok_junior
tok_junior
sprintf(hexString,"%X",atoi(decString));
should work.
_Madman_
_Madman_
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...
______Madman
tok_junior
tok_junior
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.
Skizz
Skizz
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.
Trap
Trap
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.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.