My thoughts & experiences with D so far, as a novice D coder

Chris Cain clcain at uncg.edu
Thu Mar 28 14:35:38 PDT 2013


On Thursday, 28 March 2013 at 20:24:50 UTC, Vidar Wahlberg wrote:
> that it's probably std.bitmanip I wish to use in order to 
> "convert" i.e. an int to 4 bytes (although I went first to 
> std.conv looking for this feature).

Ah, I reread it a couple of times and realized what you mean now.

You want to turn an int like 5 into an array of ubytes like 
[0,0,0,5].

So, you were on the right track, here's one way on how it's done:

---

import std.stdio, std.bitmanip, std.array;
void main() {
     auto app = appender!(ubyte[])(); // Create an appender of 
type ubyte[]
     app.append!int(5);
     writeln(app.data());
}

---

Without using appender, it's a bit more complicated:

---
import std.stdio, std.bitmanip;
void main() {
     auto buf = new ubyte[](4);
     buf.append!int(5);
     writeln(buf);
}
---

So, what append is doing is writing into the buffer, which must 
have enough space to put the int. So, thus, it must have 4 bytes. 
Guess what happens if we try to store a long in it? Yeah, it'll 
break on that as well. You'll also notice that subsequent calls 
to append on that buf will overwrite what's already in there.


It's not obvious, but append needs either an array with enough 
space to store the element or an output range, like appender. 
Maybe the documentation could use a little work in this regard.


More information about the Digitalmars-d mailing list