Should I use packed structure to simulate memory?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • cahuila
    New Member
    • Oct 2013
    • 1

    Should I use packed structure to simulate memory?

    I am trying to simulate memory in C. I want to create a structure in C that will hold a 8bit opcode and a 32bit memory address. This would simulate a 40 bit instruction for my simulator.

    I read in an old book that packed structs could be used for this to not waste space. What are the draw backs for using this? I am not worried about wasting space, but just looking for a simple way to access the memory instructions. Below is a sample of the structure that I want to use.

    Code:
    struct memory_area {
    unsigned int opcode:8;
    unsigned int address:32;
    };
    Last edited by cahuila; Oct 11 '13, 06:18 PM. Reason: Format change.
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    You also might try:

    Code:
    struct memory_area
    {
        unsigned char opcode;
        unsigned char address[4];
    };
    In this case the 40 bit instruction is opcode for the 8-bit opcode and address is the 32 bit address.


    Note that there are no character types in C or C++. A char is just an 8-bit integer. The sizeof this struct using my compiler is 5 bytes, or 40 bits.

    Personally, I don't like using bitfields as being very archaic.

    Comment

    • donbock
      Recognized Expert Top Contributor
      • Mar 2008
      • 2427

      #3
      Do all instructions in your simulated processor use exactly 40 bits? If not, then your simulated memory will have to support variable sized instructions.

      Yet another way to implement the 40-bit structure is with specific-size types:
      Code:
      struct memory_word
      {
          uint8_t opcode;
          uint32_t address;
      };
      struct memory_word memory_area[1000];

      Comment

      Working...