Use Bitwise NOT (~) Operator in JavaScript

Description

The following code shows how to use Bitwise NOT (~) Operator.

Example


<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
var iNum1 = 25;        //25 is equal to 00000000000000000000000000011001
var iNum2 = ~iNum1;    //convert to 111111111111111111111111111100110
document.writeln(iNum2);          //outputs "-26"
<!--from   w ww  . j a  v a2s .co  m-->
document.writeln("<br/>");
// integer = 32-bit binary representation
//  2 = 00000000000000000000000000000010
// -3 = 11111111111111111111111111111101
// -2 = 11111111111111111111111111111110
// -1 = 11111111111111111111111111111111
document.write("~2 = ",(~2));   //Displays -3
</script>
</body>
</html>

Click to view the demo

The code above generates the following result.

Use Bitwise NOT (~) Operator in JavaScript