Skip to content

Instantly share code, notes, and snippets.

@EvanWieland
Created December 1, 2022 21:29
Show Gist options
  • Save EvanWieland/9021020ff5e9f9d50bd35ea3583874d7 to your computer and use it in GitHub Desktop.
Save EvanWieland/9021020ff5e9f9d50bd35ea3583874d7 to your computer and use it in GitHub Desktop.
/**
* Program that masks page number and offset from an
* unsigned 32-bit address.
* The size of a page is 4 KB = 4096 Bytes(4096 = 2^12 and so n = 12 bits)
* A memory reference appears as:
* |-----------|-----|
* 31 12 11 0
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#define PAGE_NUMBER_MASK 0xFFFFF000
#define OFFSET_MASK 0x00000FFF
#define SHIFT 12
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);
// mask the page number
page_num = (reference & PAGE_NUMBER_MASK) >> SHIFT;
offset = reference & OFFSET_MASK;
printf("page number = %d\n", page_num);
printf("offset = %d\n", offset);
printf("page number = %d\n",page_num);
printf("offset = %d\n",offset);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment