print ubyte[] as (ascii) string

Tejas notrealemail at gmail.com
Thu Dec 30 16:49:17 UTC 2021


On Thursday, 30 December 2021 at 09:34:27 UTC, eugene wrote:
> I suspect the question was asked somewhere before.
> If so just give a link.
>
> Anyway:
>
> ```d
>
> class IoContext {
>     ...
>     ubyte[] buf;
>     ...
>     this(uint bufSize) {
>         buf = new ubyte[bufSize];
>     }
> }
>
> ```
>

```d
class IoContext {
      ...
      ubyte[] buf;
      ...
      this(uint bufSize) {
          buf.length = bufSize; //this should do the same thing, I 
believe
      }
}
```

> The buffer contains (ascii) string terminated with '\n'.
> In order to print it not as an array of numbers (buf is 1024 
> bytes long),
> but as usual string I do
>
> ```d
> char[] s = cast(char[])ioCtx.buf[0 .. 
> strlen(cast(char*)ioCtx.buf.ptr) - 1];
> // -1 is to eliminate terminating '\n'
> writefln("got '%s' from '%s:%d'", s, client.addr, client.port);
> ```
>

```d
char[] s = cast(char[])ioCtx.buf[0 .. $];// please remember that 
in `[0 .. $]` last index is automatically `length - 1` but just 
buf[$] will be an error since there the actual `length` will be 
used

```

I _think_ the above code is correct, please verify




More information about the Digitalmars-d-learn mailing list