'XINU OS - Understanding roundmb function

I am studying XINU OS, and came across this simple one-line function. Is it possible to explain how this function is working and rounding x to nearest block size for memory allocation? Please don't mind if the query is too simple.

I am also confused why will the change it to a char pointer.

/*----------------------------------------------------------------------

*roundmb, truncmb - round or truncate address to memory block size

*----------------------------------------------------------------------
*/

    #define roundmb(x) (char *)( (7 + (uint32)(x)) & (~7) )

Link to the complete XINU code: https://github.com/xinu-os/xinu/blob/master/include/memory.h



Solution 1:[1]

So this rounds up to the next factor of 8.

To open the incoming value is cast to be a number, so we can do proper maths on it.

First real step x + 7. This pushes the value up, so we only have to round down.

0 -> 7
1 -> 8
2 -> 10
7 -> 14
8 -> 15
9 -> 16

~7 is a bitmask, 0xFFFFFFF8. I would simplify and use 0xF8 when working it through with small numbers.

The added value is then combined with the bitmask. Basically we drop the last three bits.

0 -> 7  -> 0
1 -> 8  -> 8
2 -> 10 -> 8
7 -> 14 -> 8
8 -> 15 -> 8
9 -> 16 -> 16

This number is then cast to be a memory address, undoing the initial uint cast. Because you are dealing with memory blocks and presumably accessing data inside them it makes more sense to have it as a pointer.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 lod