0

I have a bitstring which I encoded with the function below when I try to decode with my function it doesn't work. what can I do?

def bitstring_to_bytes(self,s):
    return int(s, 2).to_bytes(len(s) // 8, byteorder='big')

def bytes_to_string(self,xbytes):
    return xbytes.from_bytes(xbytes, 'big')
  • Possible duplicate of [Convert bytes to bits in python](https://stackoverflow.com/questions/8815592/convert-bytes-to-bits-in-python) – Underoos May 15 '19 at 14:37

1 Answers1

0

(More or less) analogous to how the int type knows how to convert an integer instance to bytes, it is int again who knows how to convert bytes back to an integer.

Your xbytes variable is a bytes object, so it doesn't know how to convert itself to an integer.

Instead you do it like this:

intermediate_result = int.from_bytes(xbytes, byteorder='big')

(And afterwards you will want to convert it into a string of 0s and 1s.)

The reason it's not completely orthogonal (Converting forward you use value.method() and converting back you use type.method(value)) is that in the forward case your value is already of the type which knows how to convert itself, but in the backward case, your value is of the other type, who doesn't know how to convert back.

You can also think about it in English terms, if you like:

value.to_bytes(byteorder='big')

would be Convert this integer "value" to a bytes object.

int.from_bytes(value, byteorder='big')

would be Create a fresh integer object from that bytes "value".

blubberdiblub
  • 4,085
  • 1
  • 28
  • 30