gpt4 book ai didi

c++ - 位操作、插入、二进制

转载 作者:行者123 更新时间:2023-11-30 05:37:26 25 4
gpt4 key购买 nike

我不确定为什么有些代码格式不正确,所以如果难以阅读,我深表歉意。我正在为我的一门课学习 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;
}

最佳答案

这是我的解决方案:

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;

关于c++ - 位操作、插入、二进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33225653/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com