位操作,插入,二进制

时间:2015-10-19 23:33:13

标签: c++

我不确定为什么有些代码没有正确格式化,所以如果难以阅读,我会道歉。我正在为我的一门课学习C ++,但我被困了。我对这门语言知之甚少,所以老实说,我不知道接下来该怎么做错了。

程序应该从新数字中取四个参数,二进制数,第二个二进制数,位置号和位数。它应该从新数字中取出第一个(位数)并将它们插入原位(短)。

目标是在底部进行测试。我设法删除所有错误消息,但测试没有通过,所以我必须在某处发生逻辑错误。

#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;
}

1 个答案:

答案 0 :(得分:1)

这是我的解决方案:

df['C'] = ...