python-3.x TLV(类型长度值)数据包

vfh0ocws  于 2023-03-09  发布在  Python
关注(0)|答案(1)|浏览(128)

我正在尝试创建一个模块来打包和解包数据,如:pack:将它们编码为二进制字符串unpack:将它们从二进制字符串解码为整数:ord(decodet_binary_string),但我有很长一段时间试图继续我的代码和相同的错误显示给我编码为二进制的原因是:有些数据无法转换为utf-8或utf-16或utf-32,因此当我们将其转换为二进制字符串并编码时,我们可以使用utf-8对其进行编码:)

class tlv_packet:
        def __init__(self, bitseq = True):
                self.tlv_packet = True
                self.bitseq = bitseq

        def encode(self, data):
                self.data = ""
                if data.isascii() == True:
                        self.type = 0
                else:
                        self.type = 256
                for char in range(0, len(data)):
                        self.data += ""
                self.binary_type = bin(self.type)
                self.binary_string = "".join(f"{bin(ord(i))}" for i in data) #:08b}" for i in s)
                self.binary_length = len(self.binary_string)
                return self.binary_type, self.binary_length, self.binary_string

        def decode(self, data = ""):
                self.data_vector = data.split('b')
                self.data = ""
                for count in range(0, len(self.data_vector)):
                        char = self.data_vector[count]
                        order = 0b0
                        for char_order in range(0, len(self.data_vector[count])):
                                if self.data_vector[count][char_order] == '1':
                                        order += 1
                                elif self.data_vector[count][char_order] == '0':
                                        order += 0
                        print(self.data_vector[count])
                        self.data += chr(order)
                self.data_length = len(self.data)
                return self.data_length, self.data
zvms9eto

zvms9eto1#

解码函数的解决方案是:

def decode(self, data = ""):
            self.data_vector = data.split('0b')
            self.data_vector.remove('')
            self.data_string = ""
            for i in range(0, len(self.data_vector)):
                    self.char_order = int(self.data_vector[i], 2)
                    self.data_string += chr(self.char_order)
            self.data_length = len(self.data)
            return self.data_length, self.data_string

请在以下位置查找:convert bin string to int value in python

相关问题