magicsword
magicsword

Reputation: 1289

get a range of bytes from a bytearray

I have a bytearray:

b_arr = b'\\xff\\x02\\x04\\x01\\x00\\x02'

I want to get the last 3 bytes as:

out = 'b\\x01\\x00\\x02'

I've tried:

m = re.search("rb'\\x02\\x04'(.*)",b_arr)

But get a TypeError: TypeError: cannot use a string pattern on a bytes-like object

Upvotes: 0

Views: 2224

Answers (1)

Mark Tolonen
Mark Tolonen

Reputation: 177891

Technically, that's a bytes object, not a bytearray object and it has hex escape codes in it. This will retrieve the last three hex escape codes via string slicing:

>>> b_arr = b'\\xff\\x02\\x04\\x01\\x00\\x02'
>>> b_arr[-3*4:]
b'\\x01\\x00\\x02'

The regular expression would work if quoted correctly:

>>> b_arr = b'\\xff\\x02\\x04\\x01\\x00\\x02'
>>> import re
>>> m = re.search(rb'\\x02\\x04(.*)',b_arr)
>>> m.group(1)
b'\\x01\\x00\\x02'

Upvotes: 1

Related Questions