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?

Many thanks.

Aster
  • 59
  • 7
  • 1
    Does this answer your question? [How can I convert bytes object to decimal or binary representation in python?](https://stackoverflow.com/questions/45010682/how-can-i-convert-bytes-object-to-decimal-or-binary-representation-in-python) – Axe319 Mar 01 '21 at 16:58

1 Answers1

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
Aster
  • 59
  • 7