Luke
Luke

Reputation: 5708

Building a bit string in Python

As an exercise, I am attempting to implement an assembler for a self-defined fictitious architecture.

The only thing I'm unsure of is how to actually generate the bits. Each of my machine instructions are 2 bytes long.

For example, say I have determined that I need to generate the following byte code:

0100000100110001

This is a situation where I'm building the instruction a chunk at a time, for example, the first 3 bits are the op code, then there's some reserved bits, then a flag etc.

I figure it would be easiest to construct it as a literal string.

How can I convert a string, e.g. '0100000100110001' into the corresponding bit string and then write it to a file directly, without changing the byte ordering?

I think I might be able to use the ByteArray constructor, but I can't find any suitable examples in the docs.

Upvotes: 3

Views: 279

Answers (1)

Rolf Lussi
Rolf Lussi

Reputation: 615

You could try to write your opcode with python struct to the string. It allows to define the format of your values (int8, int16, int32, ...). So then just combine your opcode and flags to your 2 Byte code and write this with an uint16 format.

import struct

outstring = ''

code = opcode << 13
code += flags << 10
code += reg1  << 5
code += reg2 
outstring += struct.pack('H',code)

Just shift the values in the right possition. Maybe masking would be good to prevent some errors. In the end add it to your output string with struct.pack. ('H' is unsigned int 16, 'h' would be signed int 16) The whole list is in the documentation (python struct)

Upvotes: 2

Related Questions