Friday 29 June 2012

A bit on Binary.

I thought I understood binary well,but I read about 2 properties of binary numbers which convinced me I had almost zero intuition about them.

1)  a) What happens when you remove the last bit of a binary number.
      1001 >> 100
      1000  >> 100
    This behavior is just the same as dividing the number by 2. It is pretty much the same as what happens in decimal numbers,but I must mention that I couldn't realize this simple property on my own.
     In decimal system :-
     3142 >> 314
     7654 >> 765

    b) What happens when you add  a bit to a binary number
          1001>>10010
          1001>>10011
        Again,thinking about decimal numbers and seeing the following example :-
           335>>3350
           335>>3357
     Now it becomes clear,basically adding 0 at the end of any n-th base number means multiplying that number by n.I was so used to doing that for base 10,but again base 2 succeeded in confusing me.
    So 1001>>10010 means we are doubling the number.Not so obvious.Not to me atleast.
      And adding any other bit at the end at the end of a  base n number means,multiplying that number by n and adding that bit.


2) What does the number of 1's in a binary number represent?
    When I learned binary numbers the basic philosophy behind using binary was that there were only two states.Either the switch was on or off.Now the question I read was "What is the significance of the number of on or off switches there are in the number"
Again,I was clueless (and by now convinced I only had a very superficial understanding of binary system).
111011- what about the number of 0's and 1's here?
So as it turns out,any 0 or 1 at any position simply is the remainder on dividing the number,till that position ,by 2.The quotient on dividing the number by 2 is simply the number minus-the-last-digit.
Hmmm.
suppose there is a loop like
while(n){
if(n%2==1)      //Do something
n=n/2
}
Now the number of times the if condition is evaluated true is precisely the number of 1's in the binary representation of n.
I am still vague about this post.Maybe it's lame.Maybe it isn't.IDK.

UPDATE:I am very clear about this post now.I was very very foolish when I wrote it.I am not saying that I was foolish to write it.It made me clear up my mind and ask some genuine questions.To anyone,who would like to really understand bits to their lowest form,I would highly recommend reading about Bitwise Operators.I studied them for a week and now would like to believe I know how computers work,a lot better :)

No comments:

Post a Comment