ubyte[4] to int

Kyle kyle at kyle.kyle
Thu Feb 15 17:53:54 UTC 2018


On Thursday, 15 February 2018 at 17:43:10 UTC, Jonathan M Davis 
wrote:
> 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

I want to be able to pass an int to a function, then in the 
function ensure that the int is little-endian (whether it starts 
out that way or needs to be converted) before additional stuff is 
done to the passed int. The end goal is compliance with a remote 
console protocol that expects a little-endian 32-bit signed 
integer as part of a packet.

What I'm trying to achieve is to ensure that an int is in 
little-endiannes


More information about the Digitalmars-d-learn mailing list