read Hexadecimal value from string

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Tue Jul 17 15:35:29 PDT 2007


BCS wrote:
> Reply to David,
> 
>> Yep, Tango has some very kool functions. But I do want to point out
>> that Phobos does have a radix parameter in the toString functions for
>> converting a number to a string...sadly not the other way around.
>>
> 
> OK, brute force it is ;-b
> |T fromString(T)(char[] str, uint r)
> |{
> |  T v = T.min;
> |  goto start;
> |  do
> |  {
> |    v++;
> |  start:
> |    if(toString(v,r) == str) return v;
> |  }while(v != T.max);
> |}

:P

> (bonus points if you can find more than three things to object to.)

Without actually compiling that, I'll list some objections:
1) Let's get this one out of the way first: it's brute force. I mean, 
come on!
2) Since toString outputs uppercase characters (for digits > 9), this 
doesn't work for strings containing lowercase characters as digits.
3) It generates a lot of heap activity for anything that doesn't happen 
to be close to T.min (one string per iteration). Probably especially 
problematic for applications with small signed numbers or big numbers. 
This will probably mean lots of GC cycles. Arguably a symptom of (1).
4) It doesn't allow a redundant '+' at the start :P.
5) It appears from the Phobos source that toString(long value, uint 
radix) doesn't properly handle negative numbers when radix != 10. Though 
I guess that's a Phobos issue, not an issue in your code this cause the 
return value (if any[1]) answer given to be negative for T == long.

After compiling (and verifying all above issues):
6) Doesn't compile for T other than long or ulong due to overload 
resolution issues (those are the only two types toString(T, uint radix) 
is defined for).
7) Very bad error checking. Out-of-range or plain invalid input (and 
input triggering (2), (4) and/or (5)) results in a failed assertion at 
the end of the function due to no return statement being executed. And 
if compiled in release mode it segfaults (executing a 'hlt' instruction 
put there by the implicit assert(0) at the end of the function).

Did I miss anything?

[1]: Due to some of the other issues, control may reach the end of the 
function without returning anything.


More information about the Digitalmars-d-learn mailing list