Path: csiph.com!fu-berlin.de!uni-berlin.de!not-for-mail From: Julian Gethmann Newsgroups: de.comp.lang.python Subject: [Python-de] binary struct in Python Date: Thu, 20 Dec 2018 15:45:19 +0100 Lines: 43 Message-ID: References: <2456b27e-f194-d6d4-173c-ddc36d255b91@gethmann.org> Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 8bit X-Trace: news.uni-berlin.de xSCKVqgnaOJMUjYdITPL7QfqZOy2UcXxQsrchwNnjG1w== Return-Path: X-Original-To: python-de@python.org Delivered-To: python-de@mail.python.org User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Thunderbird/60.3.1 Content-Language: en-GB X-BeenThere: python-de@python.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: Die Deutsche Python Mailingliste List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-Mailman-Original-Message-ID: <2456b27e-f194-d6d4-173c-ddc36d255b91@gethmann.org> Xref: csiph.com de.comp.lang.python:5376 Hallo, ich habe binäre Daten, die ich gerne in Python Floats umwandeln würde. Leider bin ich bei der Verwendung von `structs.unpack` über das Problem gestoßen, dass meine Daten nicht nur aus floats ("f") bestehen, sondern auch chars ("c") und half-floats ("e") und letztere auf die größe von floats aufgebläht werden, wenn ich sie in einem structs entpacken will. Beispiel: Folgende Daten liegen vor (eigentlich als Datenstrom, also eher 1000 * data): ``` data = b'B\x00\x00y\xda\x00\x03\x12\xda\x00\x01!\xe2\x00\x00\x9d\xbb\r\xac\x00\x00\x00\x00\r' ``` Eigentlich könnte man sie mit "cffffefc" lesen, wenn das "c" und "e" als 1 byte und 2 byte groß angenommen würden und nicht in Kombination mit "f" als 4 byte groß, sodass statt 24 byte 29 erwartet würden. Gewünscht ist folgendes Verhalten: ``` import struct def packet_to_data(packet): Bx, TH, By, Bz = struct.unpack(">ffff", packet[1:17]) TEd = struct.unpack(">e", packet[17:19])[0] TEa = struct.unpack(">f", packet[19:23])[0] end = packet[23:24].decode("ascii") start= packet[:1].decode("ascii") if packet.startswith(b"B") and end == "\r": return Bx, By, Bz, TH, TEd, TEa ``` jedoch am Besten als Iterator, wie `struct.iter_unpack("cffffefc", data)`. Gibt es soetwas, möglichst performant, hättet ihr Vorschläge zum Optimieren meiner Funktion oder andere Vorschläge? Vielen Dank und freundliche Grüße, Julian