1

I need to cast bit sequences of arbitrary length to signed or unsigned integers. Those sequences are represented as strings. for example, I have to cast '001100100110100101110011001010' to an unsigned integer and '10000000' to a signed integer.

I used int('10000000', 2), but I haven't been able to find an intuitive approach to switch between signed/unsigned. Is there a straight-forward way to do this in Python?

Pim Klaassen
  • 95
  • 1
  • 7
  • 1
    What non-intuitive approach have you found? – martineau Apr 12 '19 at 14:50
  • @martineau maybe intuitive was not the correct word here, but I've used the library bitstring. Isn't there a way to simply do this in Python? – Pim Klaassen Apr 12 '19 at 14:57
  • How are you planning to recognize signed number without strict size of variable in bytes? `0b10000000` is `-128` if it's one byte variable and `128` it it's 2+ bytes. First bit in integer value defines sign (`0` - postive, `1` - negative). – Olvin Roght Apr 12 '19 at 15:09
  • `int('-10000000', 2)` will give you `-128` decimal—so adding a leading `-` character appears to be one way of doing it for arbitrary length sequences. – martineau Apr 12 '19 at 16:15

0 Answers0