Skip to content
Advertisement

expend valid string in byte array

array x contains string followed by all zeros. I need expand the string but keep x array’s size the same.

e.g.:

def modify(x,y):
    return x

# input x and y
x = bytes([0x41,0x42,0x43,0x44,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00])
y = 'EFGH'
print(x)
x = modify(x,y)
#output x
print(x)

expected output:

 b'ABCDx00x00x00x00x00x00x00x00x00x00x00x00'
 b'ABCDEFGHx00x00x00x00x00x00x00x00'

What’s propery way to do it in python3?

Advertisement

Answer

You can use ljust to add a number of characters to make the resulting bytes the length you want:

>>> b'ABCD'.ljust(20, b'')
b'ABCDx00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00'

So, all in all: strip the trailing zeroes out of the source bytes, add in the bit you want to add, re-pad back to the original length:

>>> x = bytes([0x41,0x42,0x43,0x44,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00])
>>> y = b'EFGH'
>>> (x.rstrip(b"x00") + y).ljust(len(x), b"x00")
b'ABCDEFGHx00x00x00x00x00x00x00x00'
>>>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement