On 14.04.2016 12:14, Carlin wrote:
import std.stdio;
import std.bitmanip;
ubyte[] serialize(uint t)
{
ubyte[] bytes = nativeToBigEndian(t);
return bytes;
}
void main()
{
writeln(serialize(0));
}
Your code is wrong. It's really easy to get wrong, though. Too easy
probably.
nativeToBigEndian returns a fixed-size array. That's a value type. By
assigning it to a ubyte[], you're slicing the return value. That is, you
make a reference to temporary data. The reference becomes invalid as
soon the assignment is over, so you're returning a slice to garbage memory.
To make a ubyte[] from the result of nativeToBigEndian, you have to dup it:
----
ubyte[] serialize(uint t)
{
return nativeToBigEndian(t).dup;
}
----