【问题标题】:C - Replacing the nth byte of a 64 bit integer [duplicate]C-替换64位整数的第n个字节[重复]
【发布时间】:2020-11-28 06:25:45
【问题描述】:

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

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

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

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

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

【问题讨论】:

    标签: c bit-manipulation


    【解决方案1】:

    试试这个:

    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
    }
    

    【讨论】:

    • 我需要对uint64_t进行一些转换吗?
    • 是的,确实如此。
    • 0xff(通常)是 32 位,byte 是 8 位,因此移位不会是 64 位。
    • 啊,谢谢。这些东西经常让我绊倒。
    • 非常感谢您的帮助!
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2011-12-08
      • 1970-01-01
      • 1970-01-01
      • 2021-08-18
      • 1970-01-01
      • 1970-01-01
      • 2011-04-21
      • 2015-04-06
      • 1970-01-01
      相关资源
      最近更新 更多