首页 > 解决方案 > C++ 仅更改 __int64 变量的低 32 位

问题描述

我有一个带有随机值的 int64 变量。我想将它的低 32 位修改为 0xf0ffffff

变量是 rdx 寄存器,但我想编辑 edx 值

ContextRecord->Rdx = 0xf0ffffff; // Not correct

标签: c++

解决方案


读取整个值,屏蔽低位,然后将其与您想要的 32 位值按位或:

#include <stdint.h>

void f(int64_t *X)
{
    *X = (*X & ~(uint64_t)0xffffffff) //mask out the lower 32 bits
         | 0xf0ffffff; //<value to set into the lower 32 bits
}

gcc并且clang在 little-endian 架构上将其优化为直接mov进入低 32 位,即相当于:

#include <string.h>

//only works on little-endian architectures
void g(int64_t *X)
{
    uint32_t y = 0xf0ffffff;
    memcpy(X,&y,sizeof(y));
}

https://gcc.godbolt.org/z/nkMSvw


推荐阅读