title: How to convert a string of bytes into an int?
body: <p>How can I convert a string of bytes into an int in python? </p>
  
  <p>Say like this: <code>'y\xcc\xa6\xbb'</code></p>
  
  <p>I came up with a clever/stupid way of doing it:</p>
  
  <pre><code>sum(ord(c) &lt;&lt; (i * 8) for i, c in enumerate('y\xcc\xa6\xbb'[::-1]))
  </code></pre>
  
  <p>I know there has to be something builtin or in the standard library that does this more simply...</p>
  
  <p>This is different from <a href="https://stackoverflow.com/questions/209513/convert-hex-string-to-int-in-python">converting a string of hex digits</a> for which you can use int(xxx, 16), but instead I want to convert a string of actual byte values.</p>
  
  <p>UPDATE:</p>
  
  <p>I kind of like James' answer a little better because it doesn't require importing another module, but Greg's method is faster:</p>
  
  <pre><code>&gt;&gt;&gt; from timeit import Timer
  &gt;&gt;&gt; Timer('struct.unpack("&lt;L", "y\xcc\xa6\xbb")[0]', 'import struct').timeit()
  0.36242198944091797
  &gt;&gt;&gt; Timer("int('y\xcc\xa6\xbb'.encode('hex'), 16)").timeit()
  1.1432669162750244
  </code></pre>
  
  <p>My hacky method:</p>
  
  <pre><code>&gt;&gt;&gt; Timer("sum(ord(c) &lt;&lt; (i * 8) for i, c in enumerate('y\xcc\xa6\xbb'[::-1]))").timeit()
  2.8819329738616943
  </code></pre>
  
  <p>FURTHER UPDATE:</p>
  
  <p>Someone asked in comments what's the problem with importing another module. Well, importing a module isn't necessarily cheap, take a look:</p>
  
  <pre><code>&gt;&gt;&gt; Timer("""import struct\nstruct.unpack("&gt;L", "y\xcc\xa6\xbb")[0]""").timeit()
  0.98822188377380371
  </code></pre>
  
  <p>Including the cost of importing the module negates almost all of the advantage that this method has. I believe that this will only include the expense of importing it once for the entire benchmark run; look what happens when I force it to reload every time:</p>
  
  <pre><code>&gt;&gt;&gt; Timer("""reload(struct)\nstruct.unpack("&gt;L", "y\xcc\xa6\xbb")[0]""", 'import struct').timeit()
  68.474128007888794
  </code></pre>
  
  <p>Needless to say, if you're doing a lot of executions of this method per one import than this becomes proportionally less of an issue. It's also probably i/o cost rather than cpu so it may depend on the capacity and load characteristics of the particular machine.</p>