Search code examples
javascriptc++binarydecimalsigned

How do I calculate how many bits are needed to represent any negative value?


I'd like to know if there's a calculation that allows me to get the number of bits that I need to store any negative (signed) value (such as -1, -255, -1324, etc.)?

At the moment I have implemented a function to calculate this for values greater and equal to 0:

calculateBitsNeeded = function (value) {

    if (value == 0) {

        return 1;
    }
    else if (value > 0) {

        return Math.floor(Math.log(value) / Math.LN2) + 1;
    }
    else {

        //TODO ...
    }
};

E.g.: If I have the number -38 I would need 7bits for storing (101 1010).

Thanks for any help :)


Solution

  • Assuming that you are talking about integer numbers.

    To answer your question, you have to understand that on all modern platforms, integers are either considered signed, or unsigned.

    JavaScript doesn't actually supports integers, they are stored as floating point values. However, a 64 bit floating point number can handle 53-bit integers with full accuracy, so it can easily handle the 16 bit integers that C uses.

    I'm going to ignore those and limit my answer to 16 bit ints that you'd use to talk to C.

    A 16 bit Unsigned bit integer can have the values of: 0 - 65535

    A signed integer can have the values of: −32,768 to 32,767

    Under both encoding, the numbers 0 - 32,767 are stored the same way. No difference in handling.

    However, the numbers 32,768 - 0 are stored using a system called two's compliment.

    Bit wise, the numbers -1 and 32,768 are the same. -2 and 32,767 are the same.

    So, the easiest way to calculate the bits needed for a negative integer is to convert it to its signed equivalent.