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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With