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

por*_*uod 8 c++ templates bit-manipulation

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

例:

int x      = 0xAAAA; // 0b1010101010101010
int y      = 0x0C30; // 0b0000110000110000
int result = 0xAC3A; // 0b1010110000111010
Run Code Online (Sandbox Code Playgroud)

这个程序有名字吗?

如果我有面具,操作很简单:

int mask_x =  0xF00F; // 0b1111000000001111
int mask_y =  0x0FF0; // 0b0000111111110000
int result = (x & mask_x) | (y & mask_y);
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚的是如何以通用的方式编写它,例如在下面的通用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
}
Run Code Online (Sandbox Code Playgroud)

问题是,当所有变量(包括整数的宽度)都是可变的时,我无法弄清楚如何正确制作掩码.

有谁知道如何正确编写上述功能?

Die*_*Epp 10

稍微移动会给你你需要的面具.

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);
}
Run Code Online (Sandbox Code Playgroud)