hello!
I want to know how you use the bitwise operators ( &, |,^, <<, >>, ~) A sample program of how they work would be helpful.
thank you!
hello!
I want to know how you use the bitwise operators ( &, |,^, <<, >>, ~) A sample program of how they work would be helpful.
thank you!
This is a simple program that counts the ones in a binary number.Code:int count_ones( unsigned x ) { int ones; /* Loop as long as x has 1 bits in it */ for( ones = 0; x != 0; x >>= 1 ) { /* If the lowest order bit is 1, count it */ if( ( x & 1 ) != 0 ) { ones += 1; } } return ones; }
pointer = NULL
I know how these work but my explanation will probably be terrible...
As you know(?) numbers are stored as bits (1's and 0's)
e.g. 10101010 == 170
>> and << shifts this number to the right or left respectively
10101010 >> 1 (shift 1 place to the right) == 01010101
10101010 << 1 == 01010100
In both cases you lose the last digit and place a zero in the first digit.
~ reverses the number
~10101010 == 01010101
~11111111 == 00000000
& | and ^ use the following tables:
had to edit this... looked really messy...Code:& : 1 : 0 | : 1 : 0 ^ : 1 : 0 1 : 1 : 0 1 : 1 : 1 1 : 0 : 1 0 : 0 : 0 0 : 1 : 0 0 : 1 : 0
operator: bit == 1 : bit == 0
bit ==1 : }
bit == 0 : } results of operations
Someone correct me if I'm wrong...
Last edited by Natase; 10-05-2001 at 11:09 AM.
Looks okay to me except for your operator tables
Here's the correct table& | and ^ use the following tables:
code:--------------------------------------------------------------------------------
& : 1 : 0 | : 1 : 0 ^ : 1 : 0
1 : 1 : 0 1 : 1 : 1 1 : 0 : 1
0 : 0 : 0 0 : 1 : 0 0 : 1 : 0
--------------------------------------------------------------------------------
Code:& : 0 : 1 | : 0 : 1 ^ : 0 : 1 0 : 0 : 0 0 : 0 : 1 0 : 0 : 1 1 : 0 : 1 1 : 1 : 1 1 : 1 : 0
pointer = NULL
Identical methinks
Hehe... I take it that's a convention?