如何在二进制形式中设置位置为1或0的数

how to set in a binary form of number at some position 1 or 0

本文关键字:位置 的数 设置 二进制      更新时间:2023-10-16

假设我有一个8位数字,我想在每个位位置设置数字1或0,这是动态的情况。

假设在这样的情况下,用户输入两个相等或相差1的数字,我希望在从0到7的每一次迭代中,将这些0和1写成二进制形式的数字,我如何在循环中实现?请帮帮我。

一个例子:

int result = 0;
for (int i = 0; i < 8; i++) {
    int x, y;
    cin >> x >> y;
    if (x == y) {
        // set at i position 0;
    }
    else if ((x-y) == 1) {
        // set  at i position 1;(in result number)
    }
}

更新:这就是我想要实现的:将两个8位的二进制补数相加下面是

的代码
#include <iostream>
using namespace std;
int main(){
          int x,y;
          cin>>x>>y;
          int result=0;
          int carry=0;
         int sum=0;
          for (int i=0;i<8;i++){
              sum=carry;
           sum+= (x&(1<<i));
           sum+=(y&(1<<i));
              if (sum>1){
               sum-=2;
               carry=1;
              }
              else{

              carry=0;
              }
              result|=sum;
              result<<=1;

          }
           cout<<result<<" "<<endl;




 return 0;
}

您可以使用AND和OR二进制操作符更改单个位。

例如:

//set first bit to 1
value |= 1;
//set fourth bit to 0
value &= ~(1<<3);
//set 6th bit to 1
value |= (1<<5);

我不知道如果你的输入相差两个会发生什么,但你可能想要这样做:

int result = 0;
for (int i = 0; i < num_bits; ++i) {
    int a, b;
    std :: cin >> a >> b;
    result |= (a != b);
    result <<= 1;
}

考虑位移位

设置位:

result |= (1<<i);

取消设置位留给读者作为练习。