Converting a ulong to a byte array and constructing a ulong from it

9898287 relay.public.adnan at outlook.com
Thu Oct 24 14:08:36 UTC 2019


On Thursday, 24 October 2019 at 13:50:54 UTC, Paul Backus wrote:
> On Thursday, 24 October 2019 at 13:33:30 UTC, 9898287 wrote:
>> What's the function for converting a ulong to a native-endian 
>> byte array?
>> For example,
>>
>> auto bytes = 0x1234567890123456u64.to_ne_bytes();
>> // should yield
>> // [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56] in 
>> big-endian and
>> // [0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12] in 
>> little-endian systems
>>
>> Also, what's the function for constructing a ulong from a 
>> native-endian byte array?
>> For example,
>>
>> auto value = from_be_bytes!ulong([0x12, 0x34, 0x56, 0x78, 
>> 0x90, 0x12, 0x34, 0x56]);
>> // value is 0x1234567890123456
>>
>> Rust equivalent:
>> https://doc.rust-lang.org/std/primitive.u64.html#method.to_ne_bytes
>
> Use a cast:
>
>     ulong m = *cast(ulong*) bytes.ptr;

Does this contain any undefined behavior? It is in C as far as I 
knew.





More information about the Digitalmars-d-learn mailing list