title: How to pack string to send to network
body: <p>I have a protocol in which I need to send few integers + strings through python socket send. For integers alone things are working fine but when string is added to the final message, receipt of the message is unable to 
  decode the string part. (I have added length before adding string)</p>
  
  <p>Please have a look at below code snippet:</p>
  
  <pre><code>userID = "abcxy"
  sample1 = struct.pack('&lt;h', LOGIN)  + struct.pack('&lt;i', len(userID)) + struct.pack('5s', userID)
  sample1 = struct.pack('&lt;h', 2 + len(sample1)) + sample1
  </code></pre>
  
  <p>sample1 generated through these steps will be :- 
  '\r\x00\x00\x00\x05\x00\x00\x00abcxy'</p>
  
  <p>When I try to decode this message in C++ using the following code I am not
  getting the correct value for userLen :- </p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;string.h&gt;
  using namespace std;
  
  int main() {
      char *ch = "'\r\x00\x00\x00\x05\x00\x00\x00arpit'";
      short len = 0, userLen= 0, code = 0;
      memcpy(&amp;len, ch, 2);
      memcpy(&amp;code, ch + 2, 2);
      memcpy(&amp;userLen, ch + 4, 4);
  }
  </code></pre>
  
  <p>Can you please help me debug what is going wrong in this case?</p>