2011-09-28 111 views
1

假設我有一個8位數字,我想在每個位置設置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; 
} 
+2

請作出努力,格式化你的散文和代碼的可讀的方式。 – spraff

回答

1

我不知道,如果你輸入的不同由會發生什麼,但你可能想是這樣的:

int result = 0; 

for (int i = 0; i < num_bits; ++i) { 
    int a, b; 
    std :: cin >> a >> b; 

    result |= (a != b); 
    result <<= 1; 
} 
1

考慮位碼移動。

要設置位:

result |= (1<<i); 

取消設置位被留下作爲鍛鍊; Tibial給讀者。

4

你可以用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); 
相關問題