Search code examples
c++cstreambinarystdio

Writing binary data in c++


I am in the process of building an assembler for a rather unusual machine that me and a few other people are building. This machine takes 18 bit instructions, and I am writing the assembler in C++.

I have collected all of the instructions into a vector of 32 bit unsigned integers, none of which is any larger than what can be represented with an 18 bit unsigned number.

However, there does not appear to be any way (as far as I can tell) to output such an unusual number of bits to a binary file in C++, can anyone help me with this.

(I would also be willing to use C's stdio and File structures. However there still does not appear to be any way to output such an arbitrary amount of bits).

Thank you for your help.

Edit: It looks like I didn't specify how the instructions will be stored in memory well enough.

Instructions are contiguous in memory. Say the instructions start at location 0 in memory:

The first instruction will be at 0. The second instruction will be at 18, the third instruction will be at 36, and so on.

There is no gaps, or no padding in the instructions. There can be a few superfluous 0s at the end of the program if needed.

The machine uses big endian instructions. So an instruction stored as 3 should map to: 000000000000000011


Solution

    • Keep an eight-bit accumulator.
    • Shift bits from the current instruction into to the accumulator until either:
      • The accumulator is full; or
      • No bits remain of the current instruction.
    • Whenever the accumulator is full:
      • Write its contents to the file and clear it.
    • Whenever no bits remain of the current instruction:
      • Move to the next instruction.
    • When no instructions remain:
      • Shift zeros into the accumulator until it is full.
      • Write its contents.
      • End.

    For n instructions, this will leave (8 - 18n mod 8) zero bits after the last instruction.