如何在某个位置设置二进制形式的数字1或0
假设我有一个八位数字,我想在每个位位置设置数字1或0,这是动态情况。
假设这样的情况,用户输入两个相等或仅相差一的数字,我希望在从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;
}
Suppose I have an eight bit number, I want to set at each bit position number 1 or zero, it is dynamic situation.
Suppose for example such situation, user enters two numbers which are equal or differs only by one, and I want that at each iteration from 0 position to seven, write these 0 and 1 in binary form of number, how can I implement it in cycle? Please help me.
An example:
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)
}
}
updated :
it is what i want to implement :
Adding two 8-bit two's complement binary numbers
here is code for this
#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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 AND 和 OR 二元运算符更改各个位。
例如:
You can change individual bits with AND and OR binary operators.
For example:
我不知道如果您的输入相差两个会发生什么,但您可能想要这样的东西:
I don't know what happens if your inputs are different by two but you might want something like this:
考虑位移位。
设置该位:
取消设置该位留给读者作为练习。
Consider bit shifting.
To set the bit:
Un-setting the bit is left as an excercise to the reader.