Is there a better way to mask bits?

-1

So I am trying to split memory addresses into their page number and offset components by masking the hex numbers. But to cover a decent variety of addresses of different bits and page sizes, I seem to have to write a lot of nested if else statements. Right now, I only have a 32-bit address size with a 4kib or 64 kib validation. Surely there is a better and less-repetitive way of doing this. I'm new to C so any help would be appreciated, thanks.

Code:

int main(void)
{
    //MemoryAddress
    unsigned int address = 0xFE03AC12;

    //Address Space
    unsigned int addressSize = calculateAddress(address);

    //Calculating Page Size
    unsigned int pageSize = 4096;
    unsigned int bits = calculatePage(pageSize);

    //Offset Mask
    unsigned int offsetMask;

    //Offset Masking Validation
    bool isValid = true;

    if (charCount == 8)
    {
        if (bits == 12 && addressSize == 32)
        {
            offsetMask = 0x00000FFF;
        }
        else if (bits == 16 && addressSize == 32)
        {
            offsetMask = 0x0000FFFF;
        }
        else
        {
            isValid = false;
            printf("Invalid!");
        }
    }
    else if (charCount == 4)
    {
        //Same code here
    }

    //Masking
    unsigned int offset = address & offsetMask;
    unsigned int vpn = address >> bits ;

    if (isValid == true)
    {
        printf("%X \t%X", vpn, offset);
    }

    return 0;
}
c
memory-address
bitmask
asked on Stack Overflow Aug 25, 2020 by Casper

1 Answer

1

For your specific example you can use:

if ((bits != 12 && bits != 16) || addressSize != 32) {
    isValid = false;
    printf("Invalid!");
} else {
    offsetMask = (1u << bits) - 1;
}

However it depends what you mean by "better". There are many different aspects like memory footprint, performance, readability.

I think the code in the question is more readable but probably less efficient than the one I proposed.

answered on Stack Overflow Aug 25, 2020 by Alex Lop. • edited Aug 25, 2020 by ryyker

User contributions licensed under CC BY-SA 3.0