Tham khảo tài liệu 'programming in python 3 - part 6', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả | 298 Chapter 7. File Handling the format will be H16s little-endian byte order 2-byte unsigned integer 16-byte byte string and the bytes object that is returned will be b x10 . Conveniently Python shows bytes objects in a compact form using printable ASCII characters where possible and hexadecimal escapes and some special escapes like t and n otherwise. The pack_string function can handle strings of up to 65535 UTF-8 characters. We could easily switch to using a different kind of integer for the byte count for example a 4-byte signed integer format i would allow for strings of up to 231-1 more than 2 billion characters. The struct module does provide a similar built-in format p that stores a single byte as a character count followed by up to 255 characters. For packing the code using p format is slightly simpler than doing all the work ourselves. But p format restricts us to a maximum of 255 UTF-8 characters and provides almost no benefit when unpacking. For the sake of comparison versions of pack_string and unpack_string that use p format are included in the source file. We can now turn our attention to the rest of the code in the export_binary method. fh None try if compress fh filename wb else fh open filename wb MAGIC FORMAT_VERSION for incident in data bytearray pack_string pack_string pack_string pack_string pack_string data return True Writing and Reading Binary Data 299 Table Bytes and Bytearray Methods 1 Syntax Description i Appends int i in range to bytearray ba Character encodings 91 width byte x start end