位操作,插入,二进制

Bit manipulation, insertion, binary

本文关键字:二进制 插入 位操作      更新时间:2023-10-16

我不知道为什么有些代码没有正确格式化,所以如果这很难阅读,我很抱歉。我正在为我的一门课学习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;