Converts the given integer to the two's complement representation. - Node.js Number

Node.js examples for Number:Int

Description

Converts the given integer to the two's complement representation.

Demo Code


/**/*www.  j  a  v  a  2  s .c  om*/
 * Converts the given integer to the two's complement representation.
 * 
 * For e.g. 0xF7 is -9 represented in two's complement using 1 byte.
 * 
 * (JavaScript's numbers are 64 bits until a bitwise operator is used on them, then they are
 *  converted to 32 bits).
 * 
 * let x = -9, and n = 8 bits
 * 
 * -x    = 0000 0000 0000 0000 0000 0000 0000 1001
 *       -                                       1 (subtract 1)
 *       = 0000 0000 0000 0000 0000 0000 0000 1000 
 *       | 1111 1111 1111 1111 1111 1111 0000 0000 (| with ~(2
 - 1))
 *       = 1111 1111 1111 1111 1111 1111 0000 1000 
 * ~x    = 0000 0000 0000 0000 0000 0000 1111 0111 = 0xF7      
 * 
 * @param {Number} integer the integer to convert
 * @param {Number} numberBytes the number of bytes representing the number (defaults to 1 if not
 *     specified)
 */
function toTwosComplement(integer, numberBytes, dontCheckRange) 
{    
    var numberBits = (numberBytes || 1) * 8;
    
    // Ensure it's in range given the number of bits
    if (!dontCheckRange && (integer < (-(1 << (numberBits - 1))) || integer > ((1 << (numberBits - 1)) - 1))) 
        throw "Integer out of range given " + numberBytes + " byte(s) to represent.";
    
    // If positive, return the positive value
    if (integer >= 0)
        return integer;
        
    // Else negative, convert to two's complement representation
    return ~(((-integer) - 1) | ~((1 << numberBits) - 1));
}

Related Tutorials