Derek
Derek

Reputation: 11

Using a bitmask to get page number and offset from a base 10 number in C

I am trying to extract a page number and offset from base 10 numbers. I am able to extract the offset with no problem, but when I try to get the page number, it simply produces the offset.

int PAGE_MASK = 255;
int OFFSET_MASK = 63;
int test_numbers[5] = { 36547, 342, 128, 1, 23650 };
int i;
for(i = 0; i < 5; i++) {
    int pg_offset = test_numbers[i] & OFFSET_MASK;
    int pg_number = test_numbers[i] & PAGE_MASK;
    printf("%s%d%s%d", "Page Number: ", pg_num, " Offset: ", pg_offset);
}

When I use this code I get the correct offset, but the incorrect page number. I was also trying to shift the bits right for the page number, but I could not get that to work either. Also, the program is assuming that all page numbers are 8 bits and all offsets are 8 bits.

Upvotes: 1

Views: 650

Answers (1)

Codor
Codor

Reputation: 17605

To my understanding, the page number can be obtained by

int pg_number = address / (PAGE_MASK + 1);

or alternatively

int pg_number = address >> 8;

but this is not actually masking, but rather an actual division.

Upvotes: 2

Related Questions