c - 从 c 中的地址中删除 LSB

标签 c bit-manipulation

<分区>

我正在尝试从一个地址中删除(意味着该位为零)LSB。下面我写的一段代码似乎没有达到我的预期。

#include<stdio.h>
#include<stdlib.h>
#include<stdint.h>
struct node
{
    unsigned long key;
    struct node* child[2];
};
int main()
{
    struct node* node = (struct node*) malloc(sizeof(struct node));
    printf("%x\n",node);
    node = (struct node*)((uintptr_t) node >> 1UL);
    printf("%x\n",node);
}

最佳答案

如果要清除最低有效位,可以使用:

(struct node*)((uintptr_t) node & (UINTPTR_MAX << 1))

但不要将结果分配给节点,否则会发生内存泄漏。

关于c - 从 c 中的地址中删除 LSB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25042705/

相关文章:

c# - 有没有一种方法可以有效地将 16 位颜色转换为 24 位颜色,同时避免 float 学运算?

python - Pandas 中返回数字而不是书籍的按位运算?

c - C:位字段和按位运算符

c - 尝试将多个信息存储到文本文件时出错

c - wchar_t 和多字节函数是 ANSI C 的一部分吗?

java - 2个箭头和3个箭头的位移位有什么区别?

c++ - 简化 (A & B) && !(A & C)

c++ - C/C++ - 如何将带符号的 32 位整数转换为 float 并返回

c - 段错误转换成二进制

c++ - 使用带或不带括号的 C 符号