Register Now

Login

Lost Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Login

Register Now

Welcome to All Test Answers

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:



/**
 * 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;
}


About

Leave a reply

Captcha Click on image to update the captcha .

error: Content is protected !!