给定两个整数 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/