如何在二进制形式中设置位置为1或0的数
how to set in a binary form of number at some position 1 or 0
假设我有一个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);
取消设置位留给读者作为练习。
相关文章:
- 关于引用数组位置的问题
- 在给定元素在螺旋上的位置的情况下,在二维数组中查找元素
- C++访问冲突读取位置0xDDDDDDCD当我尝试删除已更新的数组时
- 在不同位置渲染相同精灵的数组
- 来自不同位置的数组输出的执行时间
- 将字符数复制到新字符串位置的字符串操作,例如 S[0]
- 在动态2D布尔数组中更改一个值似乎会更改不同数组中不同位置的值
- 使用Back_inserter从任何位置的输入字符中使用Back_inserter进行过滤数组字符串
- 获取函数中已排序的数组和值,并将该值放置在正确的位置
- 查找数组位置的最大值
- 由 8 个或更多位置分隔的数组中两个元素的最大乘积
- 在 C++/CLI Visual Studio C++ 中以指定的数组位置将文本框中的值保存在 char 中
- 将名称添加到C++中的数组位置
- 如何将字符数组转换为不对齐位置的 int
- 在没有位置的数组中添加一个元素
- 如何在二进制形式中设置位置为1或0的数
- c++存储数组下一个位置的地址
- 如何在c++中表示数组位置的范围
- 数组后面的内存位置的值总是0吗?
- 获取64位整数中位位置的数组