0

I'm implementing a direct mapped cache using python which is direct mapped. Each line in cache contains 4 bytes. I'm having trouble for some reason with pulling out the first (in this case) 27 bits, and also the last 5 bits by using bit shifting.

I'm not sure what exactly I'm doing wrong in terms of bitshifting, but everything I've done is not giving me the desired bits I want. I'm doing a sort of "hard-coded" solution for now but converting the integer stored in cache to a bit string, and using python's string indexing to just get the first 27 bits, though I do want to know how to do it via bit shifting.


def getTag(d_bytes):
    b = bin(d_bytes)
    b = b[2:]
    return (b[0:27])

Is the hard-coded solution I'm referring to.

If the value stored in cache is 0b11010101010101010000100010001 I would like to have a tag of: 110101010101010100001000 (The first 27 bits, as tag = (line size - index - offset) An index of: 100 - next 3 bits following tag and an offset of: 01 (The last two bits) - last two bits

1 Answers1

1

You can extract the bits by masking and shifting.

To get the first n bits, the mask to use is 000011..(n times)..11. This mask can simply be generated with (1<<n)-1. This is equal to the number 2^n-1 whose code is exactly the mask that we want.

Now if you want to extract a bitfield that is at any position in your word, you have first to shift it right to the proper position, then use masking.

So for your problem, you can use

# extract n bits of x starting at position m
def getfield(x,n,m):
    r=x>>m  # shift it right to have lsb of bitfield at position 0
    return r&((1<<n)-1)  # then mask to extract n bits
lsb27=getfield(tag,27,0)  # get bits x[26:0]
msb5=getfield(tag,5,27)   # get bits x[31:27]
Alain Merigot
  • 10,667
  • 3
  • 18
  • 31