如何设置4字节长的底部3个字节,同时保留顶部字节不变?

And*_*man 1 c bit-manipulation bitwise-and

相关代码是这样的:

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[];
};
Run Code Online (Sandbox Code Playgroud)

举个例子,"get"宏是这样的:

//Get the size of the data contained within the chunk.
#define GET_CHUNK_SIZE(chunk) ((chunk.head) & 0xFFFFFF)
Run Code Online (Sandbox Code Playgroud)

高位字节我正在使用标志位 - "inuse"和"可以合并",而我找到的任何其他字节都是有用的.

现在我已经完成了提供背景信息,正如我在标题中所说的那样,我需要能够将较低的3个字节更改为块的大小.我最初的本能是按位和大小的标头,因为它会正确对齐,但后来我意识到它也可能会覆盖标志字节,因为它会自动加上零,直到它的大小与长整数相匹配.我甚至不确定你可以按位和一个int和一个long.无论如何,帮助非常感谢.

Jam*_*lis 7

怎么样:

head = (head & 0xff000000) | (new_size & 0x00ffffff)
Run Code Online (Sandbox Code Playgroud)


AnT*_*AnT 5

出于某种原因,到目前为止您收到的大多数回复都坚持在地毯下清除潜在的大小溢出问题,即它们“和”块大小,0x00FFFFFF从而悄悄地丢弃过大的大小位(如果有),然后继续编写完整的无意义的尾部大小入场。我不知道为什么会有人做这样的事情。

更合理的代码可能如下所示

assert((size & 0xFF000000) == 0);
chunk.head = (chunk.head & 0xFF000000) | size;
Run Code Online (Sandbox Code Playgroud)

没有正当理由用0x00FFFFFF. 您应该中止或至少断言过大的尺寸,而不是悄悄地丢弃多余的尺寸。