Reputation: 11
I am working with some page table entries and have a virtual address. Each page has data on it and the virtual address is mapped to that page.
If I have a 32 bit virtual address, how can I "grab" the first byte at a specific virtual address?
int *virtualAddress = someaddress;
int byteAtAddress = *(virtualAddress);
int secondByte = *(virtualAddress + 4);
Obviously I am getting 4 bytes instead of getting one byte. What trick can I use here to only get one byte?
Upvotes: 0
Views: 6741
Reputation: 53006
I don't understand why you ask, but still is apparently a valid question. I say "I don't understand", because you say "Obviously I am getting 4 bytes"
unsigned char *virtualAddress = comeaddress;
unsigned char byteAtAddress = virtualAddress[0];
Note, that pointer arithmetic takes consideration of the pointer type so *(virtualAddress + 4)
is1 actually adding 16 bytes to the base address.
In fact it is equivalent to
*((unsigned char *) virtualAddress + 4 * sizeof(*virtualAddress))
1Assuming you are on a regular system where sizeof(int) == 4
whichs is not necessarily true.
Upvotes: 2
Reputation: 234635
The C standard permits you to cast an address of memory that you own to an unsigned char*
:
unsigned char* p = (unsigned_char*)someaddress;
You can then extract the memory one byte at a time using pointer arithmetic on p
. Be careful not to go beyond the memory that you own - bear in mind that and int could be as small as 16 bits.
Upvotes: 4