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

标签 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[];
};

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

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

我将高位字节用于标志位——“inuse”和“can be coalesced”,以及我发现的任何其他有用的位。

既然我已完成提供背景信息,正如我在标题中所述,我需要能够将低 3 个字节更改为 block 的大小。我最初的直觉是按位对 header 与大小进行 AND 运算,因为它会正确对齐,但后来我意识到它也可能会覆盖标志字节,因为它会自动在前面加上零,直到它的大小与 long 匹配。我什至不确定您能否按位 AND 一个 int 和一个 long。无论如何,非常感谢帮助。

最佳答案

怎么样:

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

关于c - 我如何设置 4 字节长的底部 3 个字节,同时保持顶部字节不变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1806764/

相关文章:

c# - C# 是否具有与#def 常量等效的#include?

c - 从 int* 转换后,我的 char 指针指向无效值

c - 错误: sql. h:路径名中的文件或目录不存在

c - 如何使用 C 在不影响其他位的情况下替换位域中的位

c - C 中仅使用位运算符的符号函数

java - 解码自定义加密文件

python - 为什么下面代码的输出是这样的

c - 了解带有指针的 C 代码的输出

c++ - 这里到底发生了什么?

c++ - 在没有比较运算符的情况下查找 2 个数字之间的最小值