bitCast

Safely cast a value of a type to another, if both have the same size.

Unlike bruteCast, the same location si not shared between the source and the target and no pointer is used. This function is inspired by http://www.forwardscattering.org/post/27

  1. T bitCast(S s)
    template bitCast(T, S)
    pragma(inline, true)
    T
    bitCast
    (
    auto ref S s
    )
    if (
    T.sizeof == S.sizeof &&
    !is(S == T)
    &&
    !(is(S == float) & (size_t.sizeof == 4))
    &&
    !is(S == class)
    &&
    !is(T == class)
    &&
    !is(S == interface)
    &&
    !is(T == interface)
    )
  2. template bitCast(T, S)

Members

Functions

bitCast
T bitCast(S s)
Undocumented in source. Be warned that the author may not have intended to support it.

Examples

assert(bitCast!int(1.0f) == 0x3f800000);
version (LittleEndian)
	assert(bitCast!(ubyte[2])(ushort(0x1234)) == [0x34, 0x12]);
else
	assert(bitCast!(ubyte[2])(ushort(0x1234)) == [0x12, 0x34]);

Meta