Converting a ubyte[] to a struct with respect to endianness?
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Jun 23 21:10:06 PDT 2017
On 06/23/2017 07:52 PM, Felix wrote:
> So I'm guessing my ubytes are in the
> wrong order in the uint... how should I put them around the correct way
> so that my code won't break on another machine with different endianness?
Yes, that would happen when your system is little-endian. (According to
spec, the length field is big-endian.)
You can detect what endianness the system has and swap the bytes of the
length field:
http://ddili.org/ders/d.en/union.html#ix_union.endian,%20std.system
import std.system;
import core.bitop;
// ...
if (endian == Endian.littleEndian) {
address.value = bswap(address.value);
}
std.bitmanip may be useful as well:
https://dlang.org/phobos/std_bitmanip.html
Ali
More information about the Digitalmars-d-learn
mailing list