Paulo Pitta
Paulo Pitta

Reputation: 163

How to use Bitwise to extract Page Number and Offset in Language C

I am studying bitwise operators in language C, now i'm developing a paging simulator with FIFO replacement algorithm to operating systems discipline and encountered difficulties with using bitwise.


SIZE PAGE 1024                    // 1024 bits == 128 BYTES
PHYSICAL MEMORY SIZE 10           // 10 bits (PHYSICAL)
VIRTUAL MEMORY SIZE 16            // 16 bits (VIRTUAL)
NUMBER PHYSICAL PAGES 8           // 8 FRAMES
NUMBER OF VIRTUAL PAGES 512

So if we have 16 bits for virtual memory, we have logical addresses from 0 to 65535 ((2^16) -1). With this, we would have 9b for address and 7b for data.

Example with number 546 (0000 0010 0010 0010):

 Page Number  |  Offset
 0000 0010 0  |  010 0010
&1111 1111 1  |  000 0000
 0000 0010 0  |  000 0000
so, using right shift >> I get the value of the address.

The important thing is to consider the page number, the offset will be of no use. I was trying to do with text manipulation, but it did cause problems because not consider the leading zeros, which working with int and bitwise would be correct. I found an example of how to perform the extraction, but it still goes wrong even after making the necessary changes, here is the link: Click Here.

void extract_fields(unsigned int address){ ... }

If someone can help me, because I'm not sure how to apply the bitmask given the address, thank you very much, I believe that it would help a lot of people, since the doubt is something frequent and for academic purposes.

Upvotes: 5

Views: 2019

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

The only thing of importance to solving your problem is how to extract the virtual page number from the given virtual address.

This can be done with a simple bit shift by seven positions to the right (seven is the number of bits needed to address inside the 128-byte page) or with integer division by 128, which drops the remainder:

unsigned int extract_page(unsigned int address) {
    return address >> 7;
}

Use scanf("%u", &address) to read each address from the input file.

Upvotes: 2

Related Questions