Reputation: 17
I have a binary number
val = 00111010011100011000000010100000000000100000111111010
i need to convert it to an array with 8 bit elements in it like
arr = a= [{00111010},{01110001},...]
is there a simple way to do so in python?
Thanks in advance
Upvotes: 1
Views: 389
Reputation: 44838
Use the &
(bitwise AND) operator to extract the last 8 bits and the >>
(bitwise right shift) to go through the bits:
>>> val = 0b00111010011100011000000010100000000000100000111111010
>>> f"{val & 0xff:08b}"
'11111010'
>>> val >>= 8 # shift 8 bits to the right
>>> bin(val)
'0b1110100111000110000000101000000000001000001'
>>> f"{val & 0xff:08b}"
'01000001'
>>> val >>= 8
>>> f"{val & 0xff:08b}"
'00000000'
>>> val >>= 8
>>> f"{val & 0xff:08b}"
'00010100'
>>>
Here 0xff == 0b11111111
(8 1
bits)
Upvotes: 2