操作

2012-09-14 58 views
-4

可能重複:
Real world use cases of bitwise operators操作

我不太肯定位運算符&|,可有人向我解釋究竟這些運營商做什麼? 我昨天在http://www.cprogramming.com/tutorial/bitwise_operators.html上看過教程,但是我真的不知道我是否想在編碼中應用它,有人可以舉一些例子。

+6

你有沒有考慮拿起[一個很好的入門C++的書(http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list )?這樣一本書將解釋這一點以及更多。 –

+2

究竟是什麼,你不明白?你提供的教程非常廣泛 – Default

回答

0

|操作者(OR):

 
------------------------ 
a 0000 1110 1110 0101 
------------------------ 
b 1001 0011 0100 1001 
------------------------ 
a|b 1001 1111 1110 1101 

操作者給出1如果在號碼中的一個光點1

&符(AND):

 
------------------------ 
a 0000 1110 1110 0101 
------------------------ 
b 1001 0011 0100 1001 
------------------------ 
a&b 0000 0010 0100 0001 

運營商提供了0如果其中一個數字。

用法:如果我想只是數字的一部分(可以說第二組四)我可以這樣寫:

a & 0x00f0

位運算符的使用不是推薦初學者

0

這是一個非常低級的編程問題。內存的最小位是「位」。一個字節是一個8位的塊,一個字是一個16位的塊,依此類推......按位運算符讓你改變/檢查這些塊的位。取決於你正在編寫的代碼,你可能永遠不需要這些操作員。

例子:

unsigned char x = 10; /*This declares a byte and sets it to 10. The binary representation 
         of this value is 00001010. The ones and zeros are the bits.*/ 

if (x & 2) { 
    //Number 2 is binary 00000010, so the statements within this condition will be executed 
    //if the bit #1 is set (bits are numbered from right to left starting from #0) 
} 

unsigned char y = x | 1; //This makes `y` equal to x and sets the bit #0. 
         //I.e. y = 00001010 | 00000001 = 00001011 = 11 decimal