c++ - 以通用方式覆盖整数中的一系列位

标签 c++ templates bit-manipulation

给定两个整数 X 和 Y,我想将位置 P 的位覆盖到 P+N。

例子:

int x      = 0xAAAA; // 0b1010101010101010
int y      = 0x0C30; // 0b0000110000110000
int result = 0xAC3A; // 0b1010110000111010

这个过程有名字吗?

如果我有口罩,操作起来很简单:

int mask_x =  0xF00F; // 0b1111000000001111
int mask_y =  0x0FF0; // 0b0000111111110000
int result = (x & mask_x) | (y & mask_y);

我不太明白的是如何以通用方式编写它,例如在以下通用 C++ 函数中:

template<typename IntType>
IntType OverwriteBits(IntType dst, IntType src, int pos, int len) {
// If:
// dst    = 0xAAAA; // 0b1010101010101010
// src    = 0x0C30; // 0b0000110000110000
// pos    = 4                       ^
// len    = 8                ^-------
// Then:
// result = 0xAC3A; // 0b1010110000111010
}

问题是当所有变量(包括整数的宽度)都是可变的时,我不知道如何正确制作掩码。

有谁知道如何正确编写上述函数?

最佳答案

一点点改变会给你你需要的面具。

template<typename IntType>
IntType OverwriteBits(IntType dst, IntType src, int pos, int len) {
    IntType mask = (((IntType)1 << len) - 1) << pos;
    return (dst & ~mask) | (src & mask);
}

关于c++ - 以通用方式覆盖整数中的一系列位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2619866/

相关文章:

c - 将 32 位值分配给 64 位变量并保证前 32 位在 C 中为 0 的最佳方法

c# - 在标志上使用按位运算符

c++ - 在 C++ 聚合类中实现调用多路复用的优雅方式?

c++ - map 的Setter和Getter方法

c++ - Googlemock 没有捕捉到泄露的对象

c++ - 模板特化 'on the fly'

c++ - 如果多映射中与其关联的 vector 为空,则删除该键

C++ : How to make a specific binary (executable) for each trait?

c++ - 指向模板函数的空指针

c - 32 位和 64 位机器中的位操作