bytesToIntegral

Takes an array of bytes and dereferences then to an integral of your choosing

T
bytesToIntegral
(
T
)
(
ubyte[] bytes
)
if (
__traits(isIntegral, T)
)

Parameters

T

the integral type to go to

bytes ubyte[]

the bytes to copy

Return Value

Type: T

the integral but T.init if the provided size would cause an overrun read

Examples

Tests taking a byte array and then decoding it into the requested type by using bytesToIntegral!(T)(ubyte[])

In this case provided bytes match the given integral to-type

version(LittleEndian)
{
    ubyte[] bytes = [1, 0];
    ushort to = bytesToIntegral!(ushort)(bytes);
    assert(to == 1);
}
else version(BigEndian)
{
    ubyte[] bytes = [1, 0];
    ushort to = bytesToIntegral!(ushort)(bytes);
    assert(to == 256);
}

Tests taking a byte array and then decoding it into the requested type by using bytesToIntegral!(T)(ubyte[])

In this case provided bytes DO NOT match the given integral to-type and therefore to-type.init is returned

version(LittleEndian)
{
    ubyte[] bytes = [1];
    ushort to = bytesToIntegral!(ushort)(bytes);
    assert(to == ushort.init);
}
else version(BigEndian)
{
    ubyte[] bytes = [1];
    ushort to = bytesToIntegral!(ushort)(bytes);
    assert(to == ushort.init);
}

Meta