title: Convert byte array to generic type value in C#
body: <p>I would like to have a helper method for converting byte array to generic type value:</p>
  
  <pre><code>public static T BytesToValue&lt;T&gt;(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) &lt;&lt; pos;
          pos += 8;
      }
      return result;
  }
  </code></pre>
  
  <p>The problem is that the compiler gives the error.</p>
  
  <p>The method will primarily be used for getting int and long values and performance is very critical.</p>
  
  <p>How can this be fixed?</p>