bit manipulation - C Bit Operation Logic (bitAnd) -


background:
stumbled across bitwise operators in c here, , trying learn more them. searched around exercises , came across this.

however, i'm having trouble understanding first 1 "bitand."

the code reads:

/*   * bitand - x&y using ~ , |   *   example: bitand(6, 5) = 4  *   legal ops: ~ |  *   max ops: 8  *   rating: 1  */ int bitand(int x, int y) {        /* nor equivelent of , */   return ~(~x | ~y);  } 

question:
now, thought pipe ( | ) means "or." so, why need ~x , ~y? can't like:

int bitand(int x, int y) {     int or = x | y; //something 1 number or other     int , = ~or; // not or same ,     return and; } 

i wrote , ran second code sample myself (i have main function run it). -8 answer, values 6 , 5, should 4. if have "or" (the pipe operator) , "and" opposite or, why need use "~" on each value before calculate ~and?

some information/thoughts:
understand "~" flips bits in value. "or" copies bit either value other if exists (i learned here). so, if have:

6 = 00000110
,
5 = 00000101 should 0000111.

i mention show knowledge have of of operations in case understanding of wrong well.

this typical logic gates knowledge. equivalent of , gate not of nor b.

let's see happens. suppose have values such:

a = 00111 => 3 b = 01001 => 9  , b = 00001 => 1 

this expect. let's run through shared method, first one:

~a = 11000 => 24 ~b = 10110 => 22 ~a | ~b = 11110 => 30 ~(~a | ~b) = 00001 => 1 expect. 

now, let's run second proposed method.

or = 01111 => 15 , = ~or = 10000 => 16. 

now have problem. logically, this:

~(a | b) = ~a , ~b.  

is true though?

~a = 11000 => 24 ~b = 10110 => 22 ~a , ~b = 10000 => 16.  

it agrees said above, however, it's wrong can see. want 1, not 16. bitwise inverse "~" operator distributive. inverts operations well. "or" becomes "and" , "and" becomes "or". hope clears up.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -