Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read Null terminated string in python

I'm trying to read a null terminated string but i'm having issues when unpacking a char and putting it together with a string.

This is the code:

def readString(f):
    str = ''
    while True:
        char = readChar(f)
        str = str.join(char)
        if (hex(ord(char))) == '0x0':
            break           
    return str

def readChar(f):
    char = unpack('c',f.read(1))[0]
    return char

Now this is giving me this error:

TypeError: sequence item 0: expected str instance, int found

I'm also trying the following:

char = unpack('c',f.read(1)).decode("ascii")

But it throws me: AttributeError: 'tuple' object has no attribute 'decode'

I don't even know how to read the chars and add it to the string, Is there any proper way to do this?

like image 790
Seyren Windsor Avatar asked Jul 12 '26 18:07

Seyren Windsor


1 Answers

How about:

myString = myNullTerminatedString.split("\x00")[0]

For example:

myNullTerminatedString = "hello world\x00\x00\x00\x00\x00\x00"
myString = myNullTerminatedString.split("\x00")[0]
print(myString) # "hello world"

This works by splitting the string on the null character. Since the string should terminate at the first null character, we simply grab the first item in the list after splitting. split will return a list of one item if the delimiter doesn't exist, so it still works even if there's no null terminator at all.

It also will work with byte strings:

myByteString = b'hello world\x00'
myStr = myByteString.split(b'\x00')[0].decode('ascii') # "hello world" as normal string

If you're reading from a file, you can do a relatively larger read - estimate how much you'll need to read to find your null string. This is a lot faster than reading byte-by-byte. For example:

resultingStr = ''
while True:
    buf = f.read(512)
    resultingStr += buf
    if len(buf)==0: break
    if (b"\x00" in resultingStr):
        extraBytes = resultingStr.index(b"\x00")
        resultingStr = resultingStr.split(b"\x00")[0]
        break
# now "resultingStr" contains the string

f.seek(0 - extraBytes,1) # seek backwards by the number of bytes, now the pointer will be on the null byte in the file
# or f.seek(1 - extraBytes,1) to skip the null byte in the file
like image 109
fdmillion Avatar answered Jul 18 '26 06:07

fdmillion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!