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?
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.
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)
is 1 actually adding 16 bytes to the base address.
In fact it is equivalent to
*((unsigned char *) virtualAddress + 4 * sizeof(*virtualAddress))
1 Assuming you are on a regular system where sizeof(int) == 4
whichs is not necessarily true.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.