more OO way to do hex string to bytes conversion

Machin machgyl at zbor.ue
Tue Feb 6 18:59:30 UTC 2018


On Tuesday, 6 February 2018 at 18:33:02 UTC, Ralph Doncaster 
wrote:
> I've been reading std.conv and std.range, trying to figure out 
> a high-level way of converting a hex string to bytes.  The only 
> way I've been able to do it is through pointer access:
>
> import std.stdio;
> import std.string;
> import std.conv;
>
> void main()
> {
>     immutable char* hex = "deadbeef".toStringz;
>     for (auto i=0; hex[i]; i += 2)
>         writeln(to!byte(hex[i]));
> }
>
>
> While it works, I'm wondering if there is a more 
> object-oriented way of doing it in D.

converting data has nothing to do with OOP.

In D we write like that:

```
import std.range : chunks;             // consumes lazily two by 
two
import std.algorithm.iteration : map;  // apply a func to the 
chuncks
import std.conv : to;                  // the func: convert with 
a custom base
import std.array : array;              // render the whole stuff
ubyte[] a = "deadbeef".chunks(2).map!(a => a.to!ubyte(16)).array;
```


More information about the Digitalmars-d-learn mailing list