我正在为面试而学习,几个小时以来我一直在努力理解这个问题:
You are given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to set all bits between i and j in N equal to M (e.g., M becomes a substring of N located at i and starting at j).
有人可以给出一个完整的例子并说明实际需要什么吗?我是否需要设置 i 和 j 之间的值来形成 M 的值,或者实际上是 M 中的位?
是否有一些解释这些概念的关于位操作的好教程?
谢谢!
最佳答案
可以使用“masking”来实现
- 使用逐位或增量为位置 i 到 j 创建一个掩码,并将每个位设置为 1
- 使用掩码的按位 AND 和按位 NOT 消去 N 中的位
- 使用带按位与的掩码从 M 中选择位
- 使用按位或复制位
我知道我在我的例子中使用了十六进制,但同样的原则适用,只是更容易阅读。
例子
int n = 0x12345678;
int m = 0x55555555;
int i = 4; // assume right to left
int j = 15;
int mask = 0;
for (int pos = i; pos <= j; pos++) {
mask = mask | (1 << pos);
}
System.out.println(String.format("mask is 0x%08x", mask));
int nCleared = n & ~mask;
System.out.println(String.format("clear n 0x%08x", nCleared));
int bitsFromM = (m & mask);
System.out.println(String.format("Bits from m 0x%08x", bitsFromM));
int nWithM = bitsFromM | nCleared;
System.out.println(String.format("n with m 0x%08x", nWithM));
输出
mask is 0x0000fff0
clear n 0x12340008
Bits from m 0x00005550
n with m 0x12345558
关于java - 位操作修改位以包含数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27331832/