0

I would like to convert a bytearray in Python 3 in binary data in order to manipulate them.

For example, let's assume that we have the following:

a = bytearray(b'\x10\x10\x10')

Then:

a) I would like to display a in its binary form, such as b = 0b100000001000000010000.

b) I would like to be able to select some bits from the previous data (where the least significant bit would correspond to b[0] somehow), e.g., b[4:8] = 0b0001 .

How can we do that in Python?

1

1 Answer 1

1

@Axe319

Your post only partly answers my question.

Thanks to you, I got:

import sys

a = bytearray(b'\x10\x10\x10')
b = bin(int.from_bytes(a, byteorder=sys.byteorder))

print(b)
0b100000001000000010000

Then, to select four bits, I found from Python: How do I extract specific bits from a byte?:

def access_4bits(data, num):
    # access 4 bits from num-th position in data
    return bin(int(data, 2) >> num & 0b1111)

c = access_4bits(b, 4)

print(c)
0b1
Sign up to request clarification or add additional context in comments.

2 Comments

Note that the name state should be changed to a to become b = bin(int.from_bytes(a, byteorder=sys.byteorder))
Edited! It was a typo. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.