Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a slice to native (endianness) integer

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);
like image 801
Parobay Avatar asked Jun 03 '14 12:06

Parobay


1 Answers

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.

like image 183
emesx Avatar answered Oct 05 '22 03:10

emesx