ubyte[4] to int

Jonathan M Davis newsgroup.d at jmdavisprog.com
Thu Feb 15 17:43:10 UTC 2018


On Thursday, February 15, 2018 16:51:05 Kyle via Digitalmars-d-learn wrote:
> Hi. Is there a convenient way to convert a ubyte[4] into a signed
> int? I'm having trouble handling the static arrays returned by
> std.bitmanip.nativeToLittleEndian. Is there some magic sauce to
> make the static arrays into input ranges or something? As a side
> note, I'm used to using D on Linux and DMD's error messages on
> Windows are comparably terrible. Thanks!

What are you trying to do exactly? nativeToLittleEndian is going to convert
an integral type such as an int to little endian (presumably for something
like serialization). It's not going to convert to int. It converts _from_
int.

If you're trying to convert a ubyte[] to int, you'd use littleEndianToNative
or bigEndianToNative, depending on where the data comes from. You pass it a
static array of the size which matches the target type (so ubyte[4] for
int]). I don't remember if slicing a dynamic array to passi it works or not
(if it does, you have to slice it at the call site), but a cast to a static
array would work if simply slicing it doesn't.

If you're trying to convert from int to ubyte[], then you'd use
nativeToLittleEndian or nativeToBigEndian, depending on which endianness you
need. They take an integral type and give you a static array of ubyte whose
size matches the integral type.

Alternatively, if you're trying to deal with a range of ubytes, then read
and peek can be used to get integral types from a range of ubytes, and write
and append can be used to put them in a dynamic array or an output range of
ubytes.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list