how to set in a binary form of number at some position 1 or 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=开发者_JS百科1;
}
else{
carry=0;
}
result|=sum;
result<<=1;
}
cout<<result<<" "<<endl;
return 0;
}
You can change individual bits with AND and OR binary operators.
For example:
//set first bit to 1
value |= 1;
//set fourth bit to 0
value &= ~(1<<3);
//set 6th bit to 1
value |= (1<<5);
I don't know what happens if your inputs are different by two but you might want something like this:
int result = 0;
for (int i = 0; i < num_bits; ++i) {
int a, b;
std :: cin >> a >> b;
result |= (a != b);
result <<= 1;
}
Consider bit shifting.
To set the bit:
result |= (1<<i);
Un-setting the bit is left as an excercise to the reader.
精彩评论