c++中的特殊掩码操作
Special masking operation in c++
我需要使用c将变量中的每一位异或++让我们考虑4比特值a和x,其中它们的比特表示为a = a3a2a1a0
和x = x3x2x1x0
。我们将掩蔽操作"."定义为a.x = a3x3(xor)a2x2(xor)a1x1(xor)a0x0
。
我做了一个&x并找到a3x3 a2x2 a1x1 a0x0
,现在我需要对它们进行异或,但如何?有什么特别的方法吗?喜欢"&"活动我找了一下,但什么也没找到。。任何帮助都将不胜感激!
根据您的描述,您将得到的最终结果是0或1,因为您完成了安定,您需要计算安定结果的二进制表示中有多少个1:a&x.
你需要做的是逐位移位并计算1,如果最终结果是奇数,那么最终结果是1,如果是偶数,那么最后结果是0。
您需要移位"a和x"来执行所有位的异或运算。
类似于:
uint32_t a = 0xa;
uint32_t x = 0xb;
uint32_t tmp = a & x; // Bitwise AND of a and x
uint32_t res = 0;
for (int i = 0; i < 32; ++i)
{
res = res ^ (0x1 & tmp); // Only include LSB of tmp in the XOR
tmp = tmp >> 1; // Shift tmp to get a new LSB
}
cout << "Result: " << res << endl;
另一种解决方案可能是:
uint32_t a = 0xa;
uint32_t x = 0xb;
uint32_t tmp = a & x; // Bitwise AND of a and x
uint32_t res = 0;
while (tmp > 0)
{
if ((tmp % 2) == 1) res = (res + 1) & 0x1; // XOR operation
tmp = tmp/2; // Shift operation
}
cout << "Result: " << res << endl;
相关文章:
- 位移操作和位掩码未检测到重复字符
- OpenCV - 带有掩码的absdiff
- 生成前缀位掩码
- 如何从__m64值的 lsb 创建 8 位掩码?
- 如何对无符号长 int 进行位掩码?
- 删除K的背景掩码-意味着Python或C++中的集群/
- 如何在C++中优雅地处理位掩码
- 将uint64_t位掩码转换为 std::布尔数组
- 使输入二进制掩码适应 ITK 网格生成器
- 如何从 getifaddr 读取子网掩码
- 优化从子位掩码生成父位掩码
- 基于模式创建位掩码作为 constexpr
- 使用二进制掩码 C++ ITK 获取感兴趣区域
- C++中的运行时位复制(位掩码)
- 根据 IP 和掩码C++打印所有 IP
- C++设置"blank"或重置 ifstrean (ios) 的异常掩码
- OpenCV 检测带有掩码的斑点
- OPENCV:如何创建多边形形状的掩码
- 递归函数,用于使用位掩码 c++ 显示集合的所有子集
- c++中的特殊掩码操作