title: Converting list of integers into a binary "string" in python
body: <p>I have a list of numbers that i would like to send out onto a socket connection as binary data. </p>
  
  <p>As an example, i start off with the following list:</p>
  
  <pre><code>data = [2,25,0,0,ALPHA,0,23,18,188]
  </code></pre>
  
  <p>In the above list, <strong>ALPHA</strong> can be any value between 1 and 999. Initially, I was converting this into a string using</p>
  
  <pre><code> hexdata = ''.join([chr(item) for item in data])
  </code></pre>
  
  <p>So if ALPHA is 101, this would return the following string:</p>
  
  <pre><code>&gt;&gt;&gt; data = [2,25,0,0,101,0,23,18,188]
  &gt;&gt;&gt; hexdata = ''.join([chr(item) for item in data])
  &gt;&gt;&gt; hexdata
  '\x02\x19\x00\x00e\x00\x17\x12\xbc'
  </code></pre>
  
  <p>This works just fine and '\x02\x19\x00\x00e\x00\x17\x12\xbc' is the string that i need to send out.</p>
  
  <p>However, this does not work for values of ALPHA that are over 255 because its out of range of the chr statement. If for example ALPHA were 999, then i would like to get the following string:</p>
  
  <pre><code>data = [2,25,0,0,999,0,23,18,188]
  hexdata = '\x02\x19\x00\x03\xed\x00\x17\x12\xbc'
  </code></pre>
  
  <p>Ive been looking at the documentation on the struct.pack() but cannot see how that could be used to acheive the above string. ALPHA is the only variable in the list.</p>
  
  <p>Any help would be greatly appreciated.</p>
  
  <p><strong>EDIT 1</strong></p>
  
  <blockquote>
    <p>What behavior do you want? Anything
    between 256 and 65535 takes 2 bytes to
    represent. Do you want to unpack it on
    the other side? Please update the post
    with your intent. – gahooa 1 min ago</p>
  </blockquote>
  
  <p>Thats correct, since 999 is over the 256 threshold, its represented by two bytes:</p>
  
  <pre><code>data = [2,25,0,0,999,0,23,18,188]
  
  hexdata = '\x02\x19\x00**\x03\xed**\x00\x17\x12\xbc'
  </code></pre>
  
  <p>Does this make sense? </p>
  
  <p>As far as unpacking is concerned, im only sending this data out onto the socket, I will be receiving data but thats taken care of already.</p>
  
  <p><strong>EDIT 2</strong></p>
  
  <p>The string i send out is always fixed length. 
  For simplicity, I think its better to represent the list as follows:</p>
  
  <pre><code>ALPHA = 101
  
  data = [25,alpha1,alpha2,1]
  hexdata = '\x19\x00e\x01'
  
  
  ALPHA = 301
  
  data = [25,alpha1,alpha2,1]
  hexdata = 'x19\x01\x2d\x01'
  </code></pre>
  
  <p>as you can see in the hexdata string, this then becomes: \x01\x2d\</p>
  
  <p>If ALPHA &lt; 256, alpha1 = 0.</p>