如何将无符号整数连续两位改为给定值:00 01或10:
例如:
unsigned int n = 165; // 1010 0101
void changeTwoConsecutiveBits(unsigned int& n, int twoBitsValue, int positionStart)
{
assert(twoBitsValue== 0 || twoBitsValue== 1 || twoBitsValue== 2);
...
}
changeTwoConsecutiveBits(n, 2, 2);
//n == 1010 [10]01 // [1 0] is the value of twoBitsValue: 2
assert(n == 169);
n = 196; // 1100 0100
changeTwoConsecutiveBits(n, 1, 3);
//n == 110[0 1]100 // [0 1] is the value of twoBitsValue: 1
assert(n == 204);
答案 0 :(得分:1)
以下是一些示例代码,用于替换指定位给出的位置中的两位。
可能还需要检查positionStart
是否为值类型的有效位置(在本例中为unsigned int
)。
代码:
#include <assert.h>
#include <iostream>
void changeTwoConsecutiveBits(unsigned int& n, int twoBitsValue,
int positionStart) {
assert(twoBitsValue == 0 || twoBitsValue == 1 || twoBitsValue == 2);
// 0b11 or 3 if binary literal are not supported in compiler
const unsigned int inverse_mask = ~(0b11 << positionStart);
n = (n & inverse_mask) | (twoBitsValue << positionStart);
}
int main() {
unsigned int n = 165; // 1010 0101
std::cout << "n1 pre: " << n << std::endl;
changeTwoConsecutiveBits(n, 2, 2);
// n == 1010 [10]01 // [1 0] is the value of twoBitsValue: 2
assert(n == 169);
std::cout << "n1 post: " << n << std::endl;
n = 196; // 1100 0100
std::cout << "n2 pre: " << n << std::endl;
changeTwoConsecutiveBits(n, 1, 3);
// n == 110[0 1]100 // [0 1] is the value of twoBitsValue: 1
assert(n == 204);
std::cout << "n2 post: " << n << std::endl;
}