Home > Net >  expend valid string in byte array
expend valid string in byte array

Time:09-10

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'ABCD\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
 b'ABCDEFGH\x00\x00\x00\x00\x00\x00\x00\x00'

What's propery way to do it in python3?

CodePudding user response:

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

>>> b'ABCD'.ljust(20, b'\0')
b'ABCD\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

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'ABCDEFGH\x00\x00\x00\x00\x00\x00\x00\x00'
>>>
  • Related