cotro34
cotro34

Reputation: 15

Addressing memory in a simulator

Writing a simple 32-bit simulator (in C++) but managing the memory is throwing me into a loop.

My plan was to have a 2D array, the first being pointers each pointing to blocks of memory which are created on first read/write into the block.

The issue I am having is how to address it properly, if I need, for example, 216 bit addresses for memory does that mean that.

I am under the impression this would appear something like as follows

    uint32_t* m[64];
    // When first read or write into a block create as follows
    m[block] = new uint32_t[32];

This would mean the last accessible address would be 0xfffc (as 0x10000 is the total amount of addresses).

Now, if this is all correct (which I am not certain it is) I think actually getting to the memory would be as follows

    uint32_t whichBlock = addr / (32 * 4);
    uint32_t blockLoc = (addr % 32) / 4;

This seems to work for, say for example 0x80 as the address as whichBlock would be 1 and blockLoc would be 0 (i.e. the 1st word in the 2nd block) but is obviously wrong when the address is something like 0xff8c which gives whichBlock as 511 and blockLoc as 3.

Obviously I have gone completely wrong with my calculations somewhere, but I can't figure out where!

Upvotes: 1

Views: 299

Answers (1)

M.M
M.M

Reputation: 141618

So you have some rows, each of which contains 32 uint32_ts .

That means that if n is the index of the uint32_t (from 0 to 2047) then the row is n / 32 and the column is n % 32.

You didn't say how you are mapping your addresses but I assume you mean that addresses 0 through 3 are the first uint32_t and so on . If so, then divide the address by sizeof(uint32_t) to get n in my previous paragraph.

So you could have:

size_t address = 0x1234;
size_t index = address / sizeof(uint32_t);
size_t whichBlock = index / 32;
size_t blockLoc = index % 32;

Upvotes: 0

Related Questions