-4

Possible Duplicate:
Real world use cases of bitwise operators

I'm not quite sure about bitwise operator & and |, can someone explain to me what exactly these operator do? I have read tutorial in http://www.cprogramming.com/tutorial/bitwise_operators.html yesterday, butIi don't really know if I want to apply it in coding, can someone please give some examples .

Community
  • 1
  • 1
Adit
  • 9
  • 6
    Have you considered picking up [a good introductory C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)? Such a book will explain this and much more. – In silico Sep 14 '12 at 07:06
  • 2
    what exactly is it that you do not understand? The tutorial you provided is pretty extensive – default Sep 14 '12 at 07:08

2 Answers2

0

the | operator (OR):

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

the operator gives 1 if there is 1 in the spot in one of the numbers.

the & operator (AND):

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

the operator gives 0 if in one of the numbers.

usage: if I want just part of the number (lets say the second set of four) i could write:

a & 0x00f0

the usage of bit operators is not recommended for starters.

elyashiv
  • 3,623
  • 2
  • 29
  • 52
0

This is a very low-level programming question. The smallest bit of memory is the "bit". A byte is a chunk of 8 bits, a word a chunk of 16 bits and so on... Bitwise operators let you alter/check the bits of these chunks. Depending upon what you're writing code for you may never need these operators.

Examples:

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
Claudi
  • 5,224
  • 17
  • 30