Thursday, December 22, 2016

Javascript-15-Bitwise operations



Bitwise Operations


Notes: 
  • JavaScript uses 32-bit signed numbers.

Bitwise AND : 1&1 = 1, else 0


Bitwise OR0|0 = 0, else 1


Bitwise XOR1^1 = 1, 0^0 = 1, else 0


Bitwise ~ : 

~5 =>  (bitform of the number+ 1). 

  • Another trick is, ~(number) = -(number+1). ie, ~5 = -(6)

Bitwise -(negation)

However, -(5) = retain last digit and swap the rest.
ie, -5 
5 = 00000000000000000000000000000101
-5 = 11111111111111111111111111111011


(Zero Fill) Bitwise Left Shift (<<): 

  • 5 << 1 = 10; ie, 
    • 00000000000000000000000000000101 
    • <<
    • 1
    • 00000000000000000000000000001010 (ie, 000..0(2power3)0(2power1)0


(Zero Fill) Right Shift (>>>):

  • 5 >>> 1 = 2; ie, 
    • 00000000000000000000000000000101 
    • >>>
    • 1
    • 00000000000000000000000000000010 (ie, 000..0(2power1)0 == 2)

(Sign Preserving) Bitwise Right Shift (>>): 

  • -5 >> 1 = -3; ie, 
    • 11111111111111111111111111111011
    • >>
    • 1
    • =
    • 11111111111111111111111111111101 ---(a)
    • here's the trick, 
      • shift 1 place in bit format to get (a) and 
      • retain last digit after  and 
      • swap the rest. Now u get a decimal. 
      • add -ve to the obtained decimal.. hence in the above case..
      • 00000000000000000000000000000011 .. which is 3. 
      • Now add -ve to 3.. hence -3
______________________________________________

Decimal to Binary function:

function dec2bin(dec){
    return (dec >>> 0).toString(2);
}


Binary to Decimal function:

function bin2dec(bin){
    return parseInt(bin, 2).toString(10);
}


______________________________________________

No comments:

Post a Comment