Mike
Mike

Reputation: 3418

How do JavaScript Bitwise operators work?

I know bitwise operators are Bitwise Not, means 1 becomes 0 and 0 becomes 1

But my question is related to below:

var c = 5.87656778;
alert(~c);

alerts -6

var c = 5.87656778;
alert(~~c);

alert 5

Can someone throw somelight on this?

Upvotes: 1

Views: 148

Answers (2)

Joe
Joe

Reputation: 82654

They all work on 32-bit signed integers. Except for the zero-fill right shift, >>> which works on 32-bit unsigned integers.

So any float is converted to an integer via truncation.

Upvotes: 0

p.s.w.g
p.s.w.g

Reputation: 149078

Basically, it converts the number to an integer by truncating the fractional part, and performs the usual bitwise operations on that integer representation.

MDN has some pretty good documentation on this.

 5 in binary is = 00000000000000000000000000000101 =  5
                  --------------------------------
~5 in binary is = 11111111111111111111111111111010 = -6

Upvotes: 6

Related Questions