bitmanip bigEndianToNative using a buffer slice?

ketmar via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Oct 21 18:08:42 PDT 2014


On Wed, 22 Oct 2014 00:45:17 +0000
Lucas Burson via Digitalmars-d-learn
<digitalmars-d-learn at puremagic.com> wrote:

> I'm trying to create a primitive type given a specific buffer 
> slice. I can place the uint into a sliced buffer but I'm getting 
> compiler errors when using a slice to create the uint. Still new 
> to Dlang and unfamiliar with the template system.
> 
> How do I get this working?
the short answer:

 uint fromBuf =
 bigEndianToNative!uint(cast(ubyte[4])buffer[offset..offset+4]);

the long answer: you are passing dynamic array, and function is
expecting static array. slices are always dynamic by nature, so they
must be casted to static arrays before passing to bigEndianToNative.

'ubyte[4]' is not a "recomendation", it means "only static arrays will
do".

dynamic arrays are pointer to hidden "array structure" generated by
compiler, which looks like this: `struct { size_t length; void*
ptr; }`. but static arrays are just direct pointers to data, there is
no need to keep separate length, as it is known in compile time.

by casting dynamic array/slice to static array you are telling the
compiler "i know the length of the data right now, so you can use
direct pointer".

sorry if my explanations appears complex and hard to understand --
that's 'cause i'm not very good in teaching. but at least i tried and
gave the short answer too. ;-)
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 181 bytes
Desc: not available
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20141022/a8746806/attachment-0001.sig>


More information about the Digitalmars-d-learn mailing list