C program that is passed a virtual address on the command line and have it output the page number and offset for the given address
Assume that a system has a 32-bit virtual address with a 4-KB page size.
Write a C program that is passed a virtual address (in decimal) on the
command line and have it output the page number and offset for the
given address. As an example, your program would run as follows:
./a.out 19986
Your program would output:
The address 19986 contains:
page number = 4
offset = 3602
Writing this program will require using the appropriate data type to
store 32 bits.We encourage you to use unsigned data types as well.
Answer:
1234567891011121314151617181920212223242526272829303132333435363738 /**
* Program that masks page number and offset from an
* unsigned 32-bit address.
* The size of a page is 4 KB (12 bits)
*
* A memory reference appears as:
*
* |------------|-----|
* 31 12 11 0
*
*/
#
include
<stdio.h>
#
include
<unistd.h>
#define PAGE_NUMBER_MASK 0xFFFFF000
#define OFFSET_MASK 0x00000FFF
int main(int argc, char *argv[]) {
if
(argc != 2) {
fprintf
(stderr,
"Usage: ./a.out <virtual address>\n"
);
return
-1;
}
int page_num, offset;
unsigned int reference;
reference = (unsigned int)atoi(argv[1]);
printf(
"The address %d contains:\n"
,reference);
// first mask the page number
page_num = (reference & PAGE_NUMBER_MASK) >> 12;
offset = reference & OFFSET_MASK;
printf(
"page number = %d\n"
,page_num);
printf(
"offset = %d\n"
,offset);
return
0;
}
Leave a reply