I would like to have a helper method for converting byte array to generic type value:
public static T BytesToValue<T>(byte[] bytes)
{
int pos = 0;
T result = default;
foreach (byte b in bytes)
{
//Cannot convert from type byte to T error here
result |= ((T)b) << pos;
pos += 8;
}
return result;
}
The problem is that the compiler gives the error.
The method will primarily be used for getting int and long values and performance is very critical.
How can this be fixed?
BitConverter.ToInt64(byte[], int)?<<won't work either.BitConverter.ToInt64takes 3 ns.BitConverter.ToInt64uses unsafe context (so no bound-check) and loop unrolling, there's no way your version is going to be faster