Given two memory addresses address1 and address2 and a page_size, determine whether both addresses reside on the same memory page, using bitwise operations.
Two addresses are on the same page if their page numbers are equal. The page number of an address is what remains after removing the low bits that give the offset within the page, which is the same as address // page_size. page_size is guaranteed to be a power of 2.
Return True if both addresses are on the same page, or False otherwise.
Function Signature
def is_same_page(address1: int, address2: int, page_size: int) -> bool:
...
Rules
-
Pages start at address 0, so page
p
covers the addresses from
p * page_size
to
(p + 1) * page_size - 1
.
Constraints
-
0 <= address1, address2 <= 10**18
-
1 <= page_size <= 2**30
-
page_size
is a power of 2.
Examples
Input: address1 = 4096, address2 = 4100, page_size = 4096
Output: True
The page size is 212. Address 4096 is on page 1 with offset 0, and 4100 is on page 1 with offset 4, so both are on page 1.
Input: address1 = 4095, address2 = 4096, page_size = 4096
Output: False
Address 4095 is the last byte of page 0 (offset 4095), while 4096 is the first byte of page 1. They are on different pages.
Input: address1 = 5, address2 = 6, page_size = 1
Output: False
With a page size of 1 there are no offset bits, so each address is its own page. Addresses 5 and 6 are on pages 5 and 6.