C - 替换 64 位整数的第 n 个字节

C - Replacing the nth byte of a 64 bit integer

我正在尝试编写一个接受 uint64_t 并将其第 n 个字节替换为给定字节的 C 函数。

void    setByte(uint64_t *bytes, uint8_t byte, pos)

我知道我可以像这样轻松获取第 n 个字节

uint8_t getByte(uint64_t bytes, int pos)
{
     return (bytes >> (8 * pos)) & 0xff;
}

但是我不知道如何设置第n个字节

试试这个:

void setByte(uint64_t *bytes, uint8_t byte, int pos) {
    *bytes &= ~((uint64_t)0xff << (8*pos)); // Clear the current byte
    *bytes |= ((uint64_t)byte << (8*pos)); // Set the new byte
}

使用掩码将目标字节的每一位都设置为 0(即掩码应该在目标字节处全为 1 但为 0,然后与整数进行 AND 运算),然后使用另一个全为 0 的掩码但预期目标字节中的值,然后将其与整数进行或运算。