位操作,插入,二进制
Bit manipulation, insertion, binary
我不知道为什么有些代码没有正确格式化,所以如果这很难阅读,我很抱歉。我正在为我的一门课学习c++,但是我被卡住了。我对这门语言知之甚少,所以我真的不知道哪里出了问题,也不知道下一步该怎么做。
程序应该接受四个参数,一个二进制数,第二个二进制数,一个位置数和新数字的位数。它应该从新数字中取出第一个(num of bits),并将它们插入原来的位置(short)。
目标是使底部的测试通过。我设法删除了所有的错误消息,但是测试没有通过,所以我一定是在某个地方犯了逻辑错误。
#include <iostream>
#include <cassert>
#include <bitset>
#include <climits>
using namespace std;
// Return the altered bits of "input"
// where the first "numBits" of "newBits" (unspecified bits are 0)
// replace "input" bits starting at "position"
unsigned char set_bits_to(
unsigned char input,
unsigned char newBits,
short position,
short numBits){
//Your Code Here
unsigned char insert;
int x;
int i;
int q = 0;
if (input < 225) {
bitset<4> o(input);
bitset<4> d(newBits);
for (x = 0; x < numBits; x++) {
insert = o[position] = d[q];
q++;
position = position + 1;
}
}
// else {
// bitset<8> x(input);
// }(input )
//bitset<8> x(input);
//Stop Code Here
};
int main() {
assert(set_bits_to(0b1111, 0b0, 0, 1) == 0b1110);
assert(set_bits_to(0b1111, 0b0, 1, 1) == 0b1101);
assert(set_bits_to(0b1111, 0b0, 0, 3) == 0b1000);
assert(set_bits_to(0b11001100, 0b101, 2, 3) == 0b11010100);
assert(set_bits_to(0b11001100, 0b101, 2, 5) == 0b10010100);
assert(set_bits_to(0b11001100, 0b101, 3, 3) == 0b11101100);
assert(set_bits_to(0b11001100, 0b101, 5, 3) == 0b10101100);
assert(set_bits_to(0b1111, 0b101010, 0, 6) == 0b101010);
assert(set_bits_to(0b1111, 0b101010, 1, 6) == 0b1010101);
assert(set_bits_to(0b1111, 0b101010, 0, 3) == 0b1010);
cout << "All tests passed" << endl;
return 0;
}
我的解决方案是:
char insert = (~0 << numOfBits) & newBits; // these bits would be inserted
// this piece of code cleans bits between position and position - numOfBits
char positioned = ((~0 << position) | // preserves bits from position to MSB
~(~0 << (position - numOfBits)) // preservs bits from position to LSB
& input;
input = positioned & insert << position;
相关文章:
- 如何二进制搜索结构向量并在适当的索引处插入
- 在排序链表中插入结构并将其写入二进制文件
- 在二进制树插入和遍历期间,我得到了分段故障
- 分段故障插入二进制树
- 二进制搜索树插入带参数参考
- 二进制搜索树插入垃圾数据
- Mongodb C++ API 插入二进制文件(图像)
- 二进制树插入()const fpermissive误差
- 带有钩子的C 二进制树,让我知道何时/何时插入或移动节点
- 二进制树c++插入和更新
- 如何使用二进制搜索将元素插入分类的向量
- 二进制搜索树节点插入
- 插入二进制树(非BST)不起作用
- 非递归二进制树插入()方法不起作用
- C :指针与指针指针在二进制树中插入节点
- 试图理解二进制插入排序
- 避免在二进制搜索树中插入重复项
- 重载运算符 +,用于在二进制树中插入节点
- 二进制搜索树-插入
- PostgreSQL字节二进制数据插入