How to pack a struct to a ubyte[] in a more "The D way" style ?
Jonathan M Davis
newsgroup.d at jmdavisprog.com
Thu Dec 21 12:08:13 UTC 2017
On Monday, December 18, 2017 05:32:02 Binghoo Dang via Digitalmars-d-learn
wrote:
> Thanks for your idea.
>
> On Monday, 18 December 2017 at 05:08:24 UTC, Jonathan M Davis
>
> wrote:
> >> ubyte[] makeCMDPacket(RCPCmd cmd, in ubyte[] data)
> >> {
> >>
> >> this.preamble = RCPPKT_PRE;
> >> this.hdr.msgtype = RCPMSG_CMD;
> >> this.hdr.cmdcode = cast (ubyte) cmd;
> >> this.hdr.len = 0xffff & data.length;
> >
> > Why are you using & instead of simply casting to ushort?
> > Casting would be more idiomatic. Or you can use to!ushort if
> > you want to verify the size at runtime and have a ConvException
> > thrown if the value is too large.
>
> I'm using & because I'm using a C-Style. and the length needs to
> be packed into 2bytes, for casting, I don't know what will happen
> if data.length is greater. In C & C++, this kind of the cast will
> cause errors. I don't know what D will do for this.
This assertion never fails:
void main()
{
foreach(i; 0 .. uint.max)
assert((i & 0xFFFF) == cast(ushort)i);
}
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list