0

I have a python string that looks like this:

byte_string = "01100110"

I want to turn this into a byte like so:

byte_byte = some_function(byte_string) # byte_byte = 0b01100110

How can I achieve this?

SoilFoil
  • 7
  • 1

2 Answers2

0

After reflecting on the question some more, I think I originally mis-understood your intent, which is reflected in my below "Prior Answer".

I'm thinking this prior SO question may address your question as well, as it sounds like you want to convert a string of 8 bits into a single byte. And, as @Mark Ransom has indicated, it would look like this as a decimal code:

int(byte_string, 2)
output: 102

Or like this as the corresponding ascii character:

chr(int(byte_string, 2))
output: 'f'

----Prior Answer Based on Assumption of Encoding a String into an array of bytes------

You can encode a string to bytes like this, optionally passing the specific encoding if you want:

byte_string = "01100110"
byte_string.encode("utf-8")

bytes(byte_string, 'utf-8')

Result:

b'01100110'

Link to python docs for encoding / decoding strings.

Another option would be to create a bytearray:

bytearray(byte_string, 'utf-8')
output: bytearray(b'01100110')

And here is another StackOverflow thread that might be helpful as well, describing the difference between bytes and bytearray objects in relation to their use in converting to and from strings.

BioData41
  • 862
  • 9
  • 15
0

It appears you want to turn that string into a single number. For that you just convert to int with a base of 2.

byte_byte = int(byte_string, 2)
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622