Pumych
Pumych

Reputation: 1398

Bitwise operations but what is the meaning (Espruino)

What is the meaning of this line of code

n = (n<<1) | ((d>=0.0004)?1:0);

Trying to understand code from here in function sigOff() http://www.espruino.com/Remote+Control+Sockets

Upvotes: 0

Views: 120

Answers (1)

Cerbrus
Cerbrus

Reputation: 72857

This snippet seems to use the bitwise OR (|) and left shift (<<) operators:

Bitwise OR: a | b;
Returns a one in each bit position for which the corresponding bits of either or both operands are ones.
Left shift: a << b;
Shifts a in binary representation b (< 32) bits to the left, shifting in zeros from the right.

The left shift by 1 (<< 1) basically doubles the value of n.
Then, the or (|) basically "adds" 1 to the result to make it uneven, if d >= 0.0004.
If d < 0.0004, the result from the left shift isn't changed.

So, for n == 3 and d == 0.0004, this happens:

n << 1          // 6
(d>=0.0004)?1:0 // 1
6 | 1           // 7

For n == 5 and d == 0.0002, this happens:

n << 1          // 10
(d>=0.0004)?1:0 // 0
10 | 0          // 10

Upvotes: 1

Related Questions