C++ 以通用方式覆盖整数中的位范围
给定两个整数X和Y,我想覆盖位置p到p+N的位 例如:C++ 以通用方式覆盖整数中的位范围,c++,templates,bit-manipulation,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; //
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
}
模板
IntType覆盖息税(IntType dst、IntType src、int pos、int len){
//如果:
//dst=0xAAAA;//0b1010101010101010
//src=0x0C30;//0B00001100011000
//位置=4^
//len=8^-------
//然后:
//结果=0xAC3A;//0b1010110000111010
}
问题是,当所有变量(包括整数的宽度)都是变量时,我无法弄清楚如何正确地制作掩码
有人知道如何正确编写上述函数吗?您可以使用以下方法创建遮罩:
int mask_y = ((1 << len) - 1) << pos;
int mask_x = ~mask_y;
int mask_y=((1通过取((2^N+1)-1)来制作位置p到p+N的掩码,稍微移动一下将为您提供所需的掩码
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);
}
模板
IntType覆盖息税(IntType dst、IntType src、int pos、int len){
IntType mask=(((IntType)1此网站专门用于比特旋转黑客:
如果IntType
是一个long
(在大多数系统上),这将不起作用。在屏蔽整个字符串时,是否需要特殊情况?在这种情况下,它确实会溢出,但仍然会给出正确的答案。
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);
}