Skip to content

读取二进制文件中的可读字符

python
def is_printable(s):
    """Check if a string contains only printable characters."""
    return all(c.isprintable() for c in s)

def find_readable_strings(filename):
    """Find and print all readable strings from a binary file."""
    with open(filename, 'rb') as file:
        contents = file.read()

    readable_strings = []
    current_string = ""

    for byte in contents:
        if chr(byte).isprintable():
            current_string += chr(byte)
        elif current_string:
            if is_printable(current_string):
                readable_strings.append(current_string)
            current_string = ""

    if current_string and is_printable(current_string):
        readable_strings.append(current_string)

    for string in readable_strings:
        print(string)

# Usage example
find_readable_strings('a.bin')