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

Node.js examples for Number:Int

Description

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

Demo Code

/**//from w w w  .  j a v  a2s .  com
 * Converts the given two's complement representation to the represented integer.
 * 
 * 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 = 0xF7, and n = 8 bits
 * 
 * x     = 0000 0000 0000 0000 0000 0000 1111 0111
 * ~x    = 1111 1111 1111 1111 1111 1111 0000 1000
 *       & 0000 0000 0000 0000 0000 0000 1111 1111  (mask with 2
 - 1)
 *       = 0000 0000 0000 0000 0000 0000 0000 1000
 *       +                                       1  (add 1)
 *       = 0000 0000 0000 0000 0000 0000 0000 1001
 * 
 * This gives 9, then return the negation.  
 * 
 * @param {Number} twosComplement the two's complement representation
 * @param {Object} numberBytes the number of bytes representing the number (defaults to 1 if not
 *     specified)
 *
 * @return {Number} the represented integer
 */
function fromTwosComplement(twosComplement, numberBytes) 
{   
    var numberBits = (numberBytes || 1) * 8;
    
    if (twosComplement < 0 || twosComplement > (1 << numberBits) - 1)
        throw "Two's complement out of range given " + numberBytes + " byte(s) to represent.";
    
    // If less than the maximum positive: 2^(n-1)-1, the number stays positive
    if (twosComplement <= Math.pow(2, numberBits - 1) - 1)
        return twosComplement;
    
    // Else convert to it's negative representation
    return -(((~twosComplement) & ((1 << numberBits) - 1)) + 1);
}

Related Tutorials