How does the '~' operator work in JS in this case?

  • 0
    Hello !

    I'm interested in the operation of the ~ operator in js, on the Internet many people limit themselves to an example of a type. ... ...

    9 === 00000000000000000000000000001001 
    ~9 === 11111111111111111111111111110110

    From theory, it is that the ~ operator inverts every bit in the 32 two-bit representation of a number, I decided to get confused and write a function that first represents a number in a binary number system and 32 two-bit representation, and then inverts it but I don't understand one thing. ... ...

    let digit = 9;
    
    function addNullToStart(dig){ // берем число (аргумент) преобразовываем в двоичную, затем добавляем нули вачале (если конечно нужны)
        let conDig = (dig).toString(2),
            conDigLen = conDig.length,
    	    howMuchTo32 = 32 - conDigLen,
            zeroStr = '',
            res = '';
    
        if( conDigLen < 32 ){
            for(let k=0; k<howMuchTo32; k++){
                zeroStr += '0';
            };
            res = zeroStr + conDig;
        }
        return res;
    };
    
    function reverseBites(dig){ (в числе переданном аргументом меняем 1 на 0 и 0 соответственно на 1, вроде так работает ~ )
        let res = '';
        for(let k=0; k<dig.length; k++){
            if( !Number(dig[k]) ){
                res += '1'
            }else{
                res += '0';
            };
        };
        return res;
    };
    
    let convertedTo32Bits = addNullToStart( digit );
    let reversedBites32Bits =  reverseBites( convertedTo32Bits );
    
    console.log( 
             convertedTo32Bits ,  // 00000000000000000000000000001001  это 9 ( т.е наше число )
             reversedBites32Bits  // 11111111111111111111111111110110 это 4294967286 ( т.е. инверсия двоичного представления девятки )
         );


    Help me figure out where I left the right path so that I don’t remember stupidly that 9 it will be with a tilde -10 (- (n + 1)) and blah blah blah, I did everything sort of like in theory, inverted, BUT here for some reason no one explains how exactly a negative number is obtained, although for some reason this giant inverted number turns out to be negative for everyone, thanks in advance for your answer!
    JavaScript Scarlett Valenzuela, Sep 13, 2019

  • 1 Answers
  • 0
    To clearly understand the picture, refresh your memory of extra code
    Violet Cameron

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!