0

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?

7
  • 2
    You do know about casting? You could try to cast the pointer. Commented Feb 23, 2017 at 12:55
  • 1
    char *virtualAddress = someaddress; will do. Commented Feb 23, 2017 at 12:56
  • 2
    @Jean-FrançoisFabre: unsigned char*, strictly speaking. Commented Feb 23, 2017 at 12:58
  • @Bathsheba You are right, I actually just fixed my answer. Commented Feb 23, 2017 at 12:59
  • 2
    What is "the first byte"? The byte stored at the lowest address, the least significant byte of an integer, or the most significant byte of an integer? Commented Feb 23, 2017 at 13:26

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

sizeof(int) could be as low as 1. And this method does nto account for endianess or encoding. Better use shift/masks on the original int (way better: use an uint32_t).
2

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.

1 Comment

The answer asumes sizeof(int) == 4. This is not guaranteed by the standard. It could be as low as 1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.