Converting a ubyte[] to a struct with respect to endianness?

H. S. Teoh via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jun 23 22:18:02 PDT 2017


On Fri, Jun 23, 2017 at 10:10:22PM -0700, Ali Çehreli via Digitalmars-d-learn wrote:
> On 06/23/2017 09:26 PM, Felix wrote:
> > That works, thanks!
> 
> I've just tried this, which seems cleaner:
> 
> import std.stdio;
> import std.system;
> import std.bitmanip;
> 
> void ensureBigEndian(T)(ref T value) {
>     if (endian == Endian.littleEndian) {
>         value = *cast(T*)nativeToBigEndian(value).ptr;
>     }

This is wrong, you should be detecting the endianness of the input and
use {big,little}EndianToNative instead.  For example, if the input is
big endian, you should use bigEndianToNative.  Internally, if native is
already big endian, it will do nothing; otherwise it will swap the
endianness. This way you don't have to check the current machine's
endianness yourself; you can just recompile on a machine of different
endianness and it will Just Work.


T

-- 
People who are more than casually interested in computers should have at least some idea of what the underlying hardware is like. Otherwise the programs they write will be pretty weird. -- D. Knuth


More information about the Digitalmars-d-learn mailing list