Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript bitwise operator question

In JavaScript when I do this

var num = 1;

console.log(~num);  //= -2

Why does ~num not equal 0?

in binary 1 is stored as 1 ... thus not 1 should be 0

or it is stored like 0001 thus not 0001 would be 1110

I think I am missing something... can someone clear this up

like image 776
samccone Avatar asked Mar 29 '26 03:03

samccone


1 Answers

Look up Two's complement for signed binary numbers

Lets assume that a javascript Number is 8 bits wide (which its not):

then

1 = 0000 0001b

and

~1 = 1111 1110b

Which is the binary representation of -2

0000 0010b =  2
0000 0001b =  1
0000 0000b =  0
1111 1111b = -1
1111 1110b = -2
like image 113
J. Holmes Avatar answered Apr 01 '26 12:04

J. Holmes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!