Converting a ubyte[] to a struct with respect to endianness?
Steven Schveighoffer via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Jun 24 05:36:35 PDT 2017
On 6/24/17 1:18 AM, H. S. Teoh via Digitalmars-d-learn wrote:
> 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.
I would also point out that there are pre-defined versions for
endianness: version(BigEndian) and version(LittleEndian). This makes
static checking a lot easier when you are writing your own code that
deals with endiannness.
For byte-swapping one field, I would use the standard tools as H.S. has
advised.
-Steve
More information about the Digitalmars-d-learn
mailing list