3

What does (number & number) mean? I am trying to read someone's code written in JavaScript and came over with

if(misc & 0x800) {//...} //0x800 is 2048 when converted to decimal

Where var misc = 16400; //or some other number which continuously changes

So the statement is coming like if(16400 & 2048) -do something When I console.log()ed those two numbers I got 0 .

How does if statement works in case of number and number?

RegarBoy
  • 3,228
  • 1
  • 23
  • 44
  • 2
    possible duplicate of [What are bitwise operators?](http://stackoverflow.com/questions/276706/what-are-bitwise-operators) – Abhitalks Sep 07 '15 at 11:14

3 Answers3

3

One & means, that this is bitwise AND

The numbers are

16400 (10) === 100000000010000 (2)

0x800 (16) === 100000000000 (2)

Based on bitwise operation rules The result will be:

100000000010000 
   100000000000
_______________
000000000000000

Such operations oftenly used for bit masks (wiki link)

Andrey
  • 4,020
  • 21
  • 35
  • But why to use those numbers? it could be simply written as If 0. – RegarBoy Sep 07 '15 at 11:20
  • 2
    No it couldn't, because, for example, if misc will be 18448, the `18448 & 0x800` will be 2048, so it is trurhy. As you said `misc` changes continously, so your if will work depending on `misc` value. – Andrey Sep 07 '15 at 11:23
1

It is logical and operator. It first converts both data to bit and the operat.

ex.

2 & 3
--> 010 & 011
--> 010
--> 2
intekhab
  • 1,566
  • 1
  • 13
  • 19
  • If you console.log() 011 & 010 you get 8. Why so? – RegarBoy Sep 07 '15 at 12:59
  • Because 011 & 010 --> 1001 & 1000 // 011 as a number will get converted to 1001 binary and 010 will get converted to 1000 binary --> 1000 // This is binary representation --> 8 // Number representation – intekhab Sep 08 '15 at 04:32
1

It is JavaScript's BitWise Operator (See more about it here - https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators)

Bitwise '&' basically "Returns a one in each bit position for which the corresponding bits of both operands are ones." Read more in detail in the link above.

Sambhav Gore
  • 555
  • 2
  • 13