Search code examples
c#mathblock

Math, blocks and entries


I have an amount of blocks that will always be 236 bytes. And then I have some entries that need to be fitted into the blocks, these will sometimes not fit into a block perfectly so the block will be left with a few null bytes.

I am trying to work out the location be be writing the entry and what block this should be in.

        int blocklen = 236;//always the same

        int entryindex = 14;//example index of an entry to write
        int entrylength = 16;//this will be the same in all entries in these blocks.
        int blockindex = ((entryindex + 1) * entrylength) / blocklen;//this works and will correctly calculate the index of the block to write to.
        int offset = ((entryindex) * entrylength) % blocklen;// this is incorrect, I need it to work out the offset with in the block.

If my entryindex is 13 it will work out as being @ 208 in block 0, and that is right. But if it was 14 it would not fit into the first block so it should be block 1 @ 0 but instead it says block 1 at offset 224, and 224 is the offset in the first block but I need to carry it over into the next block.

Am not too good at math anyway and it's not my day so I was just wondering if any of you could help me with that line of code.


Solution

  • Your blocklen is not an even multiple of 16!

    14 * 16 = 224

    so offset will be:

    int entries_per_block = 14;
    
    int offset = (entryindex * entrylength) % (entrylength * entries_per_block);
    

    and blockindex should be:

    int blockindex = (entryindex * entrylength) / (entrylength * entries_per_block);