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

Paul Backus snarwin at gmail.com
Thu Oct 24 14:49:55 UTC 2019


On Thursday, 24 October 2019 at 14:08:36 UTC, 9898287 wrote:
> On Thursday, 24 October 2019 at 13:50:54 UTC, Paul Backus wrote:
>> Use a cast:
>>
>>     ulong m = *cast(ulong*) bytes.ptr;
>
> Does this contain any undefined behavior? It is in C as far as 
> I knew.

The equivalent code in C would use a char*, and char is allowed 
by the C standard to alias any other type [1], so it would not be 
undefined behavior.

The D language standard is less precise about this sort of thing, 
so it's hard to say with complete certainty, but the section on 
casting [2] doesn't mention anything about undefined behavior or 
strict aliasing, so it's probably fine. (It is, however, 
forbidden in @safe functions.)

[1] http://port70.net/~nsz/c/c99/n1256.html#6.5p7
[2] https://dlang.org/spec/expression.html#cast_expressions


More information about the Digitalmars-d-learn mailing list