title: How can I convert a SHA256 hash from integer to string and back?
body: <p>I would like to store a very large number of SHA256 bit hashes in MySQL.  I do not want to store them as VARCHAR(64), but rather as BIGINT.  What is the most efficient way to do the conversions in Python?  Illustration of the code I want to accomplish:</p>
  
  <pre><code>&gt;&gt;&gt; import hashlib
  &gt;&gt;&gt; s = hashlib.sha256("foo").hexdigest()
  &gt;&gt;&gt; s
  '2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae'
  &gt;&gt;&gt; i = int(s, 16)
  &gt;&gt;&gt; i
  19970150736239713706088444570146546354146685096673408908105596072151101138862L
  </code></pre>
  
  <p>Given <em>i</em>, how do I get back <em>s</em> exactly?  I have tried:</p>
  
  <pre><code>&gt;&gt;&gt; hex(i)
  '0x2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7aeL'
  </code></pre>
  
  <p>This is close but not the same.  Thanks!</p>
  
  <p>EDIT: I would like to avoid transforming the hex string like to get rid of the leading 0x and trailing L:</p>
  
  <pre><code>&gt;&gt;&gt; hex(i)[2:-1]
  '2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae'
  </code></pre>
  
  <p>Also if the hash has leading zero bits I'd have to pad zeroes until it's length 64 like:</p>
  
  <pre><code>&gt;&gt;&gt; s = "00000000000000003258ec44ea34c98111234904ef7642608922f9b8b296067d"
  &gt;&gt;&gt; i = int(s, 16)
  &gt;&gt;&gt; i
  1234513556969586830351532907052865231487419381722987759229L
  &gt;&gt;&gt; h = hex(i)[2:-1]
  &gt;&gt;&gt; h
  '3258ec44ea34c98111234904ef7642608922f9b8b296067d'
  &gt;&gt;&gt; h = "0" * (64 - len(h)) + h
  '00000000000000003258ec44ea34c98111234904ef7642608922f9b8b296067d'
  </code></pre>
  
  <p>I'd like to avoid the string manipulation.</p>