oddstray@gmail.com (oddstray) writes:
[color=blue]
> I have a number which is larger than the max unsigned long int. I
> don't have 64-bit integers available to me. I need to get the
> resulting 40-bit hex string.
>
> I have an algorithm which works, but seems alarmingly baroque ... so
> I'm hoping there's a more straightforward way. It divides the large
> value by six, converts the sixths to hex strings, and then six times
> does a character-by-character addition to construct the final hex
> string.[/color]
Reading between the lines, it seems like what you're looking for is
something that takes a 'double' holding a non-negative integral value,
and returns the string hexadecimal representation for that.
Presumably there is enough precision in whatever is holding the value
so it is represented exactly.
If that's right, try this:
char *
double_to_hex_string( double value ){
static char result[1000];
char *p = result;
char *p_bound = p + sizeof(result) - 1;
double v = value;
double a = 1.0;
if( v < 0 ) return "(value is negative)";
while( a * 16 <= v ) a *= 16;
while( a >= 1 ){
int m;
for( m = 0; m < 16 && (m + 1) * a <= v; m++ ) {}
if( p < p_bound ) *p++ = "0123456789abcdef"[ m ], *p = 0;
v -= m * a;
a /= 16;
}
return result;
}
Doing something reasonable for negative or fractional inputs is
an "exercise for the reader". Also the buffer holding the
calculated string is just a static function variable, which
isn't really good for function re-entrancy, etc; I thought it
would suffice for purposes of illustration.
By the way, I don't make any claims that there aren't some
weird corner cases or strange architectures where this code
will mess up in some unexpected way. I do think it might
solve the problem you're trying to solve.