read Hexadecimal value from string

Christopher Wright dhasenan at gmail.com
Tue Jul 17 20:11:05 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);
> |}
> 
> (bonus points if you can find more than three things to object to.)
> 
> 

1. Using a for loop would be much clearer.
2. Using a goto is generally frowned upon; local gotos, though, 
especially in such simple cases, are usually readable. However, most 
programmers react viscerally to gotos. It is recommended that you avoid 
them unless you want your viscera removed.
3. In general, you shouldn't use != for loop boundaries unless *all* 
possible values other than that single value is still valid for the guts 
of the loop. If you were to refactor and make v into a real for all 
cases, for instance, you'd do a lot more work than necessary.
4. There is not guaranteed to be a toString(T, uint) method. T is not 
guaranteed to have increment and decrement overloads.

On the plus side, this executes in constant time and is a good example 
of code reuse.

For this, though, I think I'd use annealing. It's probably a bit faster, 
especially if I had several annealings executing in parallel.


More information about the Digitalmars-d-learn mailing list