I am attempting to invert the binary digits of a base-10 value using JavaScript, according to this W3Schools page, JavaScript's Bitwise NOT operator (i.e. ~
) should do just that.
In an example they show ~5
resulting in a value of 10
, but when I attempt to execute the simple program ...
console.log(~5);
... the RTE logs -6
, not 10
. What am I doing wrong?
If you scroll down a bit at the website (https://www.w3schools.com), you find this information (as axiac has already written):
The examples above uses 4 bits unsigned binary numbers. Because of this ~ 5 returns 10.
Since JavaScript uses 32 bits signed integers, it will not return 10. It will return -6.
00000000000000000000000000000101 (5)
11111111111111111111111111111010 (~5 = -6)
A signed integer uses the leftmost bit as the minus sign.
So you didn’t do anything wrong.
var x = 5;
document.getElementById("output").innerHTML=~5;
<div id="output"></div>