strange bug with unions?

deadalnix via Digitalmars-d digitalmars-d at puremagic.com
Fri May 29 01:00:52 PDT 2015


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


More information about the Digitalmars-d mailing list