title: Behavior of ntohl and htonl different between Python and C
body: <p>I'm trying to imitate the behavior of some parts of a C program in Python. They are both reading a binary file where each record is length->data. The C program will pull the length byte from the file, and regardless of whether it's positive or negative, ntohl() will return the correct length. However, in Python, even though the length record is the same value, when it's negative I'm getting an OverflowError:</p>
  
  <blockquote>
    <p>length: 419495936</p>
    
    <p>ntohl: 281</p>
    
    <p>length: -2147418112</p>
    
    <p>OverflowError: can't convert negative number to unsigned long</p>
  </blockquote>
  
  <p>as compared to C:</p>
  
  <blockquote>
    <p>length: 419495936</p>
    
    <p>ntohl: 281</p>
    
    <p>length: -2147418112</p>
    
    <p>ntohl: 384</p>
  </blockquote>
  
  <p>What am I doing wrong here? How do I get Python to produce the same results as C?</p>
  
  <p><strong>Edit with code</strong></p>
  
  <p>Here's the C code:</p>
  
  <pre><code>while (fread(&amp;rec_len, sizeof(unsigned int),  1, fp1) != 0) {
      printf("length: %d\n", rec_len);
      rec_len = ntohl(rec_len);
      printf("ntohl: %d\n", rec_len);
  </code></pre>
  
  <p>And here's Python:</p>
  
  <pre><code>with open(file, "rb") as f:
      pSize = struct.unpack('&lt;i', f.read(4))[0]
      print "length: " + str(pSize)
      packetSize = socket.ntohl(pSize)
      print "ntohl: " + str(packetSize)
      while packetSize &gt; 0:
          packet = f.read(packetSize)
          pSize = struct.unpack('&lt;i', f.read(4))[0]
          print "length: " + str(pSize)
          packetSize = socket.ntohl(pSize)
          print "ntohl: " + str(packetSize)
  </code></pre>