Can someone explain to me bitwise operators please? I just dont seem to get it.
Thanx
ps. Can you explain it to me as if I was an idiot?
This is a discussion on bitwise operators within the C Programming forums, part of the General Programming Boards category; Can someone explain to me bitwise operators please? I just dont seem to get it. Thanx ps. Can you explain ...
Can someone explain to me bitwise operators please? I just dont seem to get it.
Thanx
ps. Can you explain it to me as if I was an idiot?
I explained these before on the old board but after just going looking for the thread the search came up with nowt so i'll explain them again....
ones complement operator ~
This just reverses a bit.....
so 0 becomes 1 and 1 becomes 0
shift right operator >>
this shifts all the bits 1 place to the right.The most significant bit becomes a zero as there isn't anything to shift in. This is a quick way of dividing integers by powers of 2.
shift left operator <<
This is the opposite of shifting to the right so this time the least significant bit is replaced by a zero and all other bits get shifted 1 place to the left.A quick way of multiplying integers by a power of 2.
bitwise and &
This is used mainly for clearing bits ( because anything anded with 0 is 0). It has the following truth table:-
a b a&b
0 0 0
0 1 0
1 0 0
1 1 1
bitwise or |
This is used mainly for setting bits (because anything ored with 1 is 1).It has the following truth table:-
a b a|b
0 0 0
0 1 1
1 0 1
1 1 1
bitwise xor ^
This is very similar to or except it doesn't produce a true result if both of its operands are true.It has this truth table.
a b a^b
0 0 0
0 1 1
1 0 1
1 1 0
here is a small code sample to print in binary...It shows how some of these operators are used.
Code:#include<stdio.h> void printbits(unsigned int tobeprinted) { unsigned int shift=8*sizeof(unsigned int)-1; // bits are 0-31 not 1-32 unsigned int mask=1<<shift; printf("%i is ",tobeprinted); for(unsigned int i=1;i<=(shift+1);i++) { if(tobeprinted &mask) printf("1"); else printf("0"); tobeprinted <<= 1; if (i%8==0) printf(" "); } } int main() { for (int i=1;i<10;i++) { printf("Enter positive integer :-"); unsigned int input; scanf("%i",&input); printbits(input); printf("\n"); } return 0; }
Free the weed!! Class B to class C is not good enough!!
And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi