1

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?

JΛYDΞV
  • 8,532
  • 3
  • 51
  • 77
Brendan Whiting
  • 494
  • 3
  • 13
  • 2
    `~5` is in fact `-6`. You're getting the correct answer. – Pointy Nov 27 '17 at 20:24
  • The example you are referring to uses 4-bit unsigned numbers. In the real world using 32-bit or 64-bit *signed* numbers, `~5` is `-6`, as you can see from the other examples on the same page. However, since the page doesn't mention it is working with 4-bit unsigned numbers it is misleading. Try to find a better tutorial, there are plenty of questions on [so] that prove that w3schools is a source of low-quality information. – axiac Nov 27 '17 at 20:30
  • I love that there's even a big yellow box that says, "Because of this ~ 5 returns 10." – Mark Nov 27 '17 at 20:32

1 Answers1

2

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>
jak.b
  • 273
  • 4
  • 15