Computer >> Computer tutorials >  >> Programming >> Javascript

Explain JavaScript Bitwise NOT, Left shift and Right shift?


JavaScript Bitwise NOT

Example

<html>
<body>
<p id="not"></p>
<script>
   document.getElementById("not").innerHTML = ~ 13;
</script>
</body>
</html>

Output

-14

Explanation: It gives 0 for 1 and 1 for 0.The above result is 14.

JavaScript Bitwise leftshift operator

Example

<html>
<body>
<p id="left"></p>
<script>
   document.getElementById("left").innerHTML = 5 << 2;
</script>
</body>
</html>

Output

20

Explanation:Left side (<<) shift operator shifts the elements to left side filling the gap with 0's.In the above example 5 in binary form is given by 0101 so when shifted by 2 it gives 010100 Which in decimal given by 20.

JavaScript Bitwise Right operator

Example

<html>
<body>
<p id="right"></p>
<script>
   document.getElementById("right").innerHTML = 5 >>> 2 ;
</script>
</body>
</html>

Output

2

Explanation: Right shift operator(>>>) in contrast to left shift operator, shifts thebits to the right .In the above example 5 got moved and the result is 1.