Convert a slice to native (endianness) integer

d, endianness, type-conversion

Solution

Taking further what Adam has written, you can write a simple function like

T sliceToNative(T)(ubyte[] slice) if(isNumeric!T) {
    const uint s = T.sizeof,
               l = min(cast(uint)s, slice.length);

    ubyte[s] padded;
    padded[0 .. l] = slice[0 .. l]; 

    return littleEndianToNative!T(padded);
}

You could even make the `littleEndianToNative` a generic type too so you mirror all the operations on arrays for slices.

Problem

I have a slice of bytes (which I know that are an integer saved as little endian) and I want to convert them to an integer. When I had a static-sized array it was no problem, but now I have a slice (`ubyte[]`). Is it possible to still convert it to an integer, e.g. in this fashion? ``` ubyte[] bytes = ...; uint native = littleEndianSliceToNative!uint(bytes); ```

Original source