Re: Merging pointers, possible? advisable?
"RyanMcCoskrie" wrote:
This is a very bizarre Q but is it possible to merge two pointers (for
want of a better term) into a pointer
to one pointer that is the sum of the first two values.
It's for my little virtual machine project (emulator at the moment
anyhow).
All addresses refer to a byte in a large array but this makes working
with larger values awkward
particularly since addresses are stored as words.
The logical solution seems to be to treat values in the RAM as either
two bytes or one sixteen bit word
depending on the context.
Then again I have an issue of being out of sight from the box that
most people think in.
Your wording in the first part in confusing. You have an array of char like
so the following?
unsigned char memory[somesize];
Now you would like to be able to access say a 16 bit integer that begins at
say location 2050 (for example)?
If so what you want is something along the lines of:
word_t* aWord = reinterpret_cast<word_t*>(&memory[2050]);
Where word_t is a typedef for some unsigned integer type with a size of 16
bits on the platform you are using. In this example, *aWord would be the
value of locations 2050 and 2051 interpeted as a 16 bit integer. Of course,
you would need to be careful about the possibilty that the desired byte
order (little endian or big endian) of the VM and the byte order of the
machine the code is running on is not the same.
For storing back into the memory you would use the following:
*reinterpret_cast<word_t>(&memory[2050])=aWord;
A slightly better solution would be something like this:
// This implemention stores words in big endian
// format, but that is easy to change)
class Memory
{
public:
Memory(size_t size) : mem(size){ }
unsigned char getByteAt(std::size_t addr)
{ return mem[addr]; }
void SetByteAt(std::size_t addr, value)
{ mem[addr]=value; }
word_t getWordt(std::size_t addr)
{ return (mem[addr]<<8)+mem[addr+1];}
void SetWordAt(std::size_t addr, value)
{ mem[addr]=(value>>8); mem[addr+1]=value&0xff; }
private:
std::vector<byte> mem;
}
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]