strange bug with unions?
seen via Digitalmars-d
digitalmars-d at puremagic.com
Fri May 29 01:15:25 PDT 2015
On Friday, 29 May 2015 at 08:00:54 UTC, deadalnix wrote:
> On Friday, 29 May 2015 at 07:55:55 UTC, seen wrote:
>> I don't know why but when using a template union with a static
>> ubyte array i get bizarre results!
>>
>> module main;
>>
>> import std.stdio;
>> private union ByteConverter(T)
>> {
>> ubyte[T.sizeof] bytes;
>> T value;
>> }
>>
>> ubyte[] toBytes(T)(T from) if (!is(T == const))
>> {
>> ByteConverter!T converter;
>> converter.value = from;
>> return converter.bytes;
>> }
>>
>> T fromBytes(T)(in ubyte[] bytes)
>> {
>> ByteConverter!T converter;
>> converter.bytes = bytes;
>> return converter.value;
>> }
>>
>> void main(string[] args)
>> {
>> writeln(fromBytes!uint(toBytes(34u)));// should print 32 but
>> prints 1244564
>> }
>>
>> why dose it print 1244564 the array is static size so why is
>> it acting like bytes is a pointer not a static array?
>
> http://fr.wikipedia.org/wiki/Endianness#Little_endian
endianness should not be an issue since I'm not changing machines
and using static array unions is a common way to convert to bytes
in D.
More information about the Digitalmars-d
mailing list