title: Formula to convert byte array representing signed integer into integer
body: <p>This question is more generic without a particular language. I am more interested in solving this generally across languages. Every answer I find references a built-in method of something like <code>getInt32</code> to extract an integer from a byte array.</p>
  
  <p>I have a byte array which contains the big-endian representation of a signed integer.</p>
  
  <pre><code>1 -&gt; [0, 0, 0, 1]
  -1 -&gt; [255, 255, 255, 255]
  -65535 -&gt; [255, 255, 0, 1]
  </code></pre>
  
  <p>Getting the values for the positive cases are easy:</p>
  
  <pre><code>arr[3] | arr[2] &lt;&lt; 8 | arr[1] &lt;&lt; 16 | arr[0] &lt;&lt; 24
  </code></pre>
  
  <p>What I would like to figure out is the more general case. I have been reading about 2s complement, which lead me to the python function from Wikipedia:</p>
  
  <pre><code>def twos_complement(input_value, num_bits):
      '''Calculates a two's complement integer from the given input value's bits'''
      mask = 2**(num_bits - 1) - 1
      return -(input_value &amp; mask) + (input_value &amp; ~mask)
  </code></pre>
  
  <p>which in turn lead me to produce this function:</p>
  
  <pre><code># Note that the mask from the wiki function has an additional - 1
  mask = 2**(32 - 1)
  def arr_to_int(arr):
      uint_val = arr[3] | arr[2] &lt;&lt; 8 | arr[1] &lt;&lt; 16 | arr[0] &lt;&lt; 24
      if (determine_if_negative(uint_val)):
          return -(uint_val &amp; mask) + (uint_val &amp; ~mask)
      else:
          return uint_val
  </code></pre>
  
  <p>In order for my function to work I need to fill in <code>determine_if_negative</code> (I should mask the signed bit and check if it is 1). But is there a standard formula to handle this? One thing I found is that in some languages, like Go, the bitshift might overflow the int value. </p>
  
  <p>This is pretty hard to search because I get a thousand results explaining the difference between big-endian and little-endian or results explaining twos complement, and many more giving examples of using the standard library but I haven't seen a complete formula for bitwise functions.</p>
  
  <p>Is there a canonical example in C or similar language of converting a char array using only array access and bitwise functions (ie, no memcpy or pointer casting or tricky stuff)</p>