[英]How to change unsigned integer two consecutive bits
How to change unsigned integer two consecutive bits by a given value: 00 01 or 10: 如何用给定值00 00或10更改两个连续无符号整数位:
For example: 例如:
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);
Here is some sample code that replace the two bits in a position given by the indicated bits. 这是一些示例代码,这些代码在指示的位给定的位置替换了两位。
Probably need also to check that positionStart
is valid position for value type (in this case unsigned int
). 可能还需要检查
positionStart
是值类型的有效位置(在这种情况下为unsigned int
)。
Code: 码:
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.