Search code examples
cbit-manipulationbitwise-and

How might I set the bottom 3 bytes of a 4-byte long while leaving the top byte intact?


Relevant code is this:

typedef unsigned long int chunk_head;

typedef struct malloc_chunk
{
    // Contains the size of the data in the chunk and the flag byte.
    chunk_head      head;

    // Deliberately left unsized to allow overflow. 
    // Contains the payload of the chunk.
    unsigned int    data[];
};

And just as an example, the "get" macro is this:

//Get the size of the data contained within the chunk.
#define GET_CHUNK_SIZE(chunk) ((chunk.head) & 0xFFFFFF)

The upper byte I'm using the bits for flags -- "inuse" and "can be coalesced", and any additional ones that I find will be useful.

Now that I'm done providing background information, as I stated in the title, I need to be able to change the lower 3 bytes to how large the chunk is. My initial instinct was to bitwise AND the header with the size, since it would be properly aligned, but then I realized it might overwrite the flag bytes too, because it automatically prepended zeroes until it size matched the long. I'm not even sure you can bitwise AND an int and a long. Anyway, help greatly appreciated.


Solution

  • How about:

    head = (head & 0xff000000) | (new_size & 0x00ffffff)