Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More Pythonic conversion to binary?

Tags:

python

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:

  • Every line starts with data.append(struct.pack(, distracting from the unique part of the line.
  • The byte order ('<') is repeated over and over again.
  • You have to remember to return the boilerplate ''.join(data).

What I like:

  • The format specifiers appear near the attribute name. E.g., it's easy to see that self.image.size is written out as two unsigned ints.
  • The lines are (mostly) independent. E.g., To remove the Id field from an 'attribute', you don't have to touch more than one line of code.

Is there a more readable/pythonic way to do this?

like image 682
Jon-Eric Avatar asked May 21 '09 17:05

Jon-Eric


People also ask

How do you convert to binary in Python?

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.

How do I convert decimal to binary?

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.


1 Answers

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()
like image 103
Dave Avatar answered Sep 29 '22 07:09

Dave