Here is a contrived example of how a lot of our classes return binary representations (to be read by C++) of themselves.
def to_binary(self):
    'Return the binary representation as a string.'
    data = []
    # Binary version number.
    data.append(struct.pack('<I', [2]))
    # Image size.
    data.append(struct.pack('<II', *self.image.size))
    # Attribute count.
    data.append(struct.pack('<I', len(self.attributes)))
    # Attributes.
    for attribute in self.attributes:
        # Id.
        data.append(struct.pack('<I', attribute.id))
        # Type.
        data.append(struct.pack('<H', attribute.type))
        # Extra Type.        
        if attribute.type == 0:
            data.append(struct.pack('<I', attribute.typeEx))
    return ''.join(data)
What I dislike:
data.append(struct.pack(, distracting from the unique part of the line.'<') is repeated over and over again.''.join(data).What I like:
self.image.size is written out as two unsigned ints.Is there a more readable/pythonic way to do this?
In Python, you can simply use the bin() function to convert from a decimal value to its corresponding binary value. And similarly, the int() function to convert a binary to its decimal value. The int() function takes as second argument the base of the number to be converted, which is 2 in case of binary numbers.
Take decimal number as dividend. Divide this number by 2 (2 is base of binary so divisor here). Store the remainder in an array (it will be either 0 or 1 because of divisor 2). Repeat the above two steps until the number is greater than zero.
from StringIO import StringIO
import struct
class BinaryIO(StringIO):
    def writepack(self, fmt, *values):
        self.write(struct.pack('<' + fmt, *values))
def to_binary_example():
    data = BinaryIO()
    data.writepack('I', 42)
    data.writepack('II', 1, 2)
    return data.getvalue()
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With