ubyte[4] to int
Ali Çehreli
acehreli at yahoo.com
Thu Feb 15 18:39:41 UTC 2018
On 02/15/2018 09:53 AM, Kyle wrote:
> 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.
As has been said elsewhere, the value of an int is just that value. The
value does not have endianness. Yes, different CPUs layout values
differently in memory but that has nothing with your problem below.
> The end goal is compliance with a remote console protocol that
> expects a little-endian 32-bit signed integer as part of a packet.
So, they want the value to be represented as 4 bytes in little endian
ordering. I think all you need to do is to call nativeToLittleEndian:
https://dlang.org/phobos/std_bitmanip.html#nativeToLittleEndian
If your CPU is already little-endian, it's a no-op. If not, the bytes
would be swapped accordingly:
import std.stdio;
import std.bitmanip;
void main() {
auto i = 42;
auto result = nativeToLittleEndian(i);
foreach (b; result) {
writefln("%02x", b);
}
// Note: The bytes of i may have been swapped
writeln("May not be 42, and that's ok: ", i);
}
Prints the following on my Intel CPU:
2a
00
00
00
May not be 42, and that's ok: 42
Ali
More information about the Digitalmars-d-learn
mailing list