read Hexadecimal value from string

BCS BCS at pathlink.com
Wed Jul 18 10:16:29 PDT 2007


Christopher Wright wrote:
> 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.

i++
> 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.

i++
//AAAaahh!!! ;)

> 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.
i++

> 4. There is not guaranteed to be a toString(T, uint) method. T is not 
> guaranteed to have increment and decrement overloads.
> 
i+=2

> 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.

i-= large_number
// that's even worse then mine!!

//nice breakdown (bonus points to you)


More information about the Digitalmars-d-learn mailing list