Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python byte array to bit array

I want to parse some data with Python and scapy. Therefor I have to analyse single bits. But at the moment I have for example UDP packets with some payload like:

bytes = b'\x18\x00\x03\x61\xFF\xFF\x00\x05\x42\xFF\xFF\xFF\xFF'

Is there any elegant way to convert the bytes so that I can access single bits like:

bytes_as_bits = convert(bytes)
bit_at_index_42 = bytes_as_bits[42]
like image 519
N. Stra Avatar asked May 04 '17 15:05

N. Stra


2 Answers

>>> n=17
>>> [(n & (1<<x))>>x for x in [7,6,5,4,3,2,1,0]]
[0, 0, 0, 1, 0, 0, 0, 1]
like image 191
Atila Romero Avatar answered Sep 30 '22 17:09

Atila Romero


That will work:

def access_bit(data, num):
    base = int(num // 8)
    shift = int(num % 8)
    return (data[base] >> shift) & 0x1

If you'd like to create a binary array you can use it like this:

[access_bit(data,i) for i in range(len(data)*8)]
like image 33
Liran Funaro Avatar answered Sep 30 '22 19:09

Liran Funaro