Split an address into tag, index and offset

A cache cuts every address into a tag, an index and an offset. Work out the widths for a cache and split one address.

What to build

A program that prints the bit widths of the three fields and the fields of one address.

Requirements

  • Block size, number of lines and ways are powers of two. There are lines ÷ ways sets.
  • Print offset bits O, index bits I and tag bits T.
  • Then print tag X set Y offset Z with the three fields of the given address, as decimal numbers.

Input

One line: address bits, block size, lines, ways, and the address (a decimal number below 2 to the power of the address bits).

Output

Four lines.

Constraints

Address bits are from 8 to 32; ways divides lines; the block size is from 1 to 256.

Example

Input:

16 16 8 2 4660

Output:

offset bits 4
index bits 2
tag bits 10
tag 72 set 3 offset 4

Why it works

The low bits choose the byte in the block, the next bits choose the set, and everything above them is the tag. Shifts and masks cut the three fields out of the address.

Examples

Example 1 · Input
16 16 8 2 4660
Expected output
offset bits 4
index bits 2
tag bits 10
tag 72 set 3 offset 4
Example 2 · Input
8 1 4 4 200
Expected output
offset bits 0
index bits 0
tag bits 8
tag 200 set 0 offset 0

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

offset bits = log2(block size); sets = lines ÷ ways; index bits = log2(sets). In Python, n.bit_length() - 1 is log2 of a power of two.

Hint 2

tag bits = address bits - index bits - offset bits.

Hint 3

offset = a & (block - 1); index = (a >> offset bits) & (sets - 1); tag = a >> (offset bits + index bits).

Solution

Show one correct solution (try it yourself first)
bits, block, lines, ways, address = map(int, input().split())
sets = lines // ways
ob = block.bit_length() - 1
ib = sets.bit_length() - 1
tb = bits - ob - ib
print("offset bits", ob)
print("index bits", ib)
print("tag bits", tb)
print("tag", address >> (ob + ib), "set", (address >> ob) & (sets - 1), "offset", address & (block - 1))

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Cache memory →