Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitwise operations on non numbers

Somehow, JavaScript makes sense of the bitwise operations NaN ^ 1, Infinity ^ 1 and even 'a' ^ 1 (all evaluate to 1).

What are the rules governing bitwise operators on non numbers? Why do all the examples above evaluate to 1?

like image 639
Randomblue Avatar asked Jun 14 '12 16:06

Randomblue


People also ask

What is bitwise not of 1?

Overview# Bitwise NOT (or complement) is a Bitwise operation, is a unary operation that performs logical negation on each bit, forming the ones' complement of the given binary value. Bits that are 0 become 1, and those that are 1 become 0. Bitwise NOT is equal to the two's complement of the value minus one.

How do you perform bitwise NOT operation?

The bitwise NOT operator in C++ is the tilde character ~ . Unlike & and |, the bitwise NOT operator is applied to a single operand to its right. Bitwise NOT changes each bit to its opposite: 0 becomes 1, and 1 becomes 0.

Which is not a valid bitwise operator?

Which of these is not a bitwise operator? Explanation: <= is a relational operator.


1 Answers

According to the ES5 spec, when doing bitwise operations, all operands are converted to ToInt32 (which first calls ToNumber. If the value is NaN or Infinity, it's converted to 0).

Thus: NaN ^ 1 => 0 XOR 1 => 1

like image 162
Rocket Hazmat Avatar answered Sep 28 '22 06:09

Rocket Hazmat