close

轉貼我自己2008 8/6的文章

 

今天自己寫了一次N皇后的回溯程式,結果發現位元運算有些地方並不如我想像一般,所以今天把所有地方重新做一次整理,其中包括我之前就知道的

關於!與~

#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <algorithm>

using namespace std;

int main()
{
    int a=1;
    
    printf("%d %d\n", !a, ~a);
    
    system("PAUSE");
    
    return EXIT_SUCCESS;
}

本段程式碼輸出結果: 0 -2

下列以1Byte舉例

因為00000001

每位數取相反為11111110,正好為二的捕數法的-2

而!呢,只是取Boolean值的相反,跟位元運算無關

改成這樣

a=5;
   
printf("%d %d\n", !a, ~a);

將會輸出0 -6,即可證明

另外 || 、 | 與 &&、&之間的關係類似

|、&是針對每一個數字位元去做運算,而||、&&皆是布林值運算

#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <algorithm>

using namespace std;

int main()
{
    int a=3, b=2;
   
    printf("%d %d\n", a&&b, a||b);
       
   
    system("PAUSE");
   
    return EXIT_SUCCESS;
}

輸出結果 1 1

分解動作→3為true 2為true,則AND之後→true

#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <algorithm>

using namespace std;

int main()
{
    int a=3, b=2;
   
    printf("%d %d\n", a&b, a|b);
       
   
    system("PAUSE");
   
    return EXIT_SUCCESS;
}


如果是這樣的話,輸出結果 2 3

看成二進位制的運算
11 & 10 = 10 ; 11 | 10 = 11

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 robertanders 的頭像
    robertanders

    Robert Anderson's Blog

    robertanders 發表在 痞客邦 留言(0) 人氣()