How to convert signed string to its Binary equivalent in Python?
<p>I am using the itertool function to enter value to a list. The itertool function is taking the value as a str, not as an int. After that, I need to convert the values from the list to its Binary equivalent. The problem arises when I need to convert a negative value e.g. -5. My code is taking the "-" as a str, but I need it to consider it as a negative sign before the following numerical value.Does the concept of unsigned integer come into play?</p>

<p>My code is-</p>

<pre><code>L3= list(itertools.repeat("-1",5))

file= open(filename, 'w')

L3_1=[ ]

for item in L3:

       x3=bytes(item,"ascii")
       L3_1.append(' '.join(["{0:b}".format(x).zfill(8) for x in x3]))

for item in L3_1:

       file.write("%s\n" % item)

file.close()
</code></pre>

<p>It's not entirely clear what your problem is and what you want to achieve, so please correct me if I make wrong assumptions.</p>

<p>Anyways, converting integers to binary representation is easily done using <code>bin</code>. For example, <code>bin(5)</code> gives you <code>'0b101'</code>. Now, <code>bin(-5)</code> gives you <code>'-0b101'</code> - which is not what you expect when being used to binary from other languages, e.g. C.</p>

<p>The "problem" is that integers in python are <em>not</em> fixed size. There's no <code>int16</code>, <code>int32</code>, <code>uint8</code> and such. Python will just add bits as it needs to. That means a negative number <strong>cannot</strong> be represented by its complement - <code>0b11111011</code> is not <code>-5</code> as for <code>int8</code>, but 251. Since binaries are potentially infinite, there's no fixed position to place a sign bit. Thus, python has to add the explicit unary <code>-</code>. This is <em>different</em> from interpreting <code>-5</code> as the strings <code>"-"</code> and <code>"5"</code>.</p>

<p>If you want to get the binary representation for negative, <em>fixed size</em> integers, I think you have to do it by yourself. A function that does this could look like this:</p>

<pre><code>def bin_int(number, size=8):
    max_val = int('0b' + ('1'* (size - 1)), 2)  # e.g. 0b01111111
    assert -max_val &lt;= number &lt;= max_val, 'Number out of range'
    if number &gt;=0:
        return bin(number)
    sign = int('0b1' + ('0' * size), 2)  # e.g. 0b10000000
    return bin(number + sign)
</code></pre>

<p>Now, to do what you initially wanted: write the binary representation of numbers to a file.</p>

<pre><code>output_list = [1, -1, -5, -64, 0]  # iterable *containing* integers
with open(filename, 'w') as output_file:  # with statement is safer for writing
    for number in output_list:
        output_file.write(bin_int(number) + '\n')
</code></pre>

<p>Or if you just want to check the result:</p>

<pre><code>print([bin_int(number) for number in [1, -1, -5, -64, -127]])
# ['0b1', '0b11111111', '0b11111011', '0b11000000', '0b10000001']
</code></pre>

<p>Note that if you want to strip the <code>0b</code>, you can do that via <code>bin_int(number)[2:]</code>, e.g. <code>output_file.write(bin_int(number)[2:] + '\n')</code>. This removes the first two characters from the string holding the binary representation.</p>

python