How can i add bytearrays In python?

182 views Asked by At

I'm new in python. I have a bytearray of shellcode:

a=bytearray('\x31\xcb\x50\x69').

What i have to do is to +1 to every each of them to have this result:

bytearray('\x32\xcc\x51\x6a').

Any good ideas how I can achieve these in python?

Thank you and best regards,

3

There are 3 answers

2
kindall On
a = bytearray('\x31\xcb\x50\x69')
a = bytearray(b + 1 if b < 255 else 0 for b in a)

Change the 0 to 255 if you want to clip the value rather than wrappping back around to zero.

3
John La Rooy On
>>> a=bytearray('\x31\xcb\x50\x69')
>>> a
bytearray(b'1\xcbPi')    # repr uses a different but equivalent representation
>>> bytearray(x + 1 for x in a)
bytearray(b'2\xccQj')

You will need to consider what it means to +1 to 0xff

for example

bytearray((x + 1) % 0xff for x in a)  # wrap around

or

bytearray(min(x + 1), 0xff) for x in a)  # limit to 0xff

It's probably faster to use the translate method if you are doing a few of these

>>> trans_table = bytearray(range(1, 256)) + '\x00'
>>> a.translate(trans_table)
bytearray(b'2\xccQj')

If you want to print the arrays to look like that, use the repr() function

>>> print a
1�Pi
>>> print repr(a)
bytearray(b'1\xcbPi')
0
Marcin On

You can do as follows:

a=bytearray('\x31\xcb\x50\x69')
new_a = bytearray(b + 1 for b in a)


for b in new_a:
    print('{:02x}'.format(b))

Outputs:

32
cc
51
6a