转换为字节数组
(self)
| 46 | return self.channel_bits_used |
| 47 | |
| 48 | def to_bytes(self): |
| 49 | """转换为字节数组""" |
| 50 | filename_bytes = self.filename.encode('utf-8') |
| 51 | filename_len = len(filename_bytes) |
| 52 | |
| 53 | if filename_len > self.MAX_FILENAME_LENGTH: |
| 54 | raise ValueError(f"文件名编码后长度超过{self.MAX_FILENAME_LENGTH}字节") |
| 55 | |
| 56 | # 构建头数据 |
| 57 | header = bytearray() |
| 58 | |
| 59 | # 1. DATA_STAMP (9字节) |
| 60 | header.extend(self.DATA_STAMP) |
| 61 | |
| 62 | # 2. HEADER_VERSION (1字节) |
| 63 | header.extend(self.HEADER_VERSION) |
| 64 | |
| 65 | # 3. FIXED_HEADER (8字节) |
| 66 | # dataLength (4字节,小端序) |
| 67 | header.extend(struct.pack('<I', self.data_length)) |
| 68 | # channelBitsUsed (1字节) |
| 69 | header.append(self.channel_bits_used) |
| 70 | # fileNameLen (1字节) |
| 71 | header.append(filename_len) |
| 72 | # useCompression (1字节) |
| 73 | use_compression = 1 if (self.config and self.config.is_use_compression()) else 0 |
| 74 | header.append(use_compression) |
| 75 | # useEncryption (1字节) |
| 76 | use_encryption = 1 if (self.config and self.config.is_use_encryption()) else 0 |
| 77 | header.append(use_encryption) |
| 78 | |
| 79 | # 4. CRYPT_ALGO (8字节) |
| 80 | if self.config and self.config.get_encryption_algorithm(): |
| 81 | crypt_algo = self.config.get_encryption_algorithm().encode('utf-8') |
| 82 | # 截断或填充到8字节 |
| 83 | if len(crypt_algo) > self.CRYPT_ALGO_LENGTH: |
| 84 | crypt_algo = crypt_algo[:self.CRYPT_ALGO_LENGTH] |
| 85 | else: |
| 86 | crypt_algo = crypt_algo.ljust(self.CRYPT_ALGO_LENGTH, b' ') |
| 87 | else: |
| 88 | crypt_algo = b' ' * self.CRYPT_ALGO_LENGTH |
| 89 | header.extend(crypt_algo) |
| 90 | |
| 91 | # 5. fileName (变长) |
| 92 | if filename_len > 0: |
| 93 | header.extend(filename_bytes) |
| 94 | |
| 95 | return bytes(header) |
| 96 | |
| 97 | @staticmethod |
| 98 | def from_bytes(data, config=None): |
no test coverage detected