Convert a signed decimal to hex encoded with two's complement

diffa picture diffa · May 27, 2011 · Viewed 11k times · Source

I need to encode a signed integer as hexadecimal using via the two's complement notation. For example I would like to convert

e.g. -24375 to 0xffffa0c9.

So far I have been working on the following lines:

parseInt(-24375).toString(2)
> "-101111100110111"    

This matches what Wolfram Alpha displays, but I am not sure how to get to the signed 24bit int representation of the number (ffffa0c9).

I've worked out how to take the unsigned binary number and represent this as two's complement:

~ parseInt("101111100110111", 2) + 1
> -23475

but I am not sure get the binary representation of this number to convert to hex.

Any ideas?

Answer

Paul Rumkin picture Paul Rumkin · Mar 25, 2019

To create two's-compliment numbers of fixed size I've created factory method:

 function createToInt(size) {
    if (size < 2) {
        throw new Error('Minimum size is 2');
    }
    else if (size > 64) {
        throw new Error('Maximum size is 64');
    }

    // Determine value range
    const maxValue = (1 << (size - 1)) - 1;
    const minValue = -maxValue - 1;

    return (value) => {
        if (value > maxValue || value < minValue) {
            throw new Error(`Int${size} overflow`);
        }

        if (value < 0) {
            return (1 << size) + value;
        }
        else {
            return value;
        }
    };
}

Now, to solve your question you can create functions toInt8, toInt16, toInt32, etc. And use it to convert JS numbers to two's compliment. Example with int8:

const toInt8 = createToInt(8);

'0x' + toInt8(-128).toString(16); // -> 0x80
'0x' + toInt8(127).toString(16); // -> 0x7f
'0x' + toInt8(-1).toString(16); // -> 0xff

// Values less then 16 should be padded
'0x' + toInt8(10).toString(16).padStart(2, '0); // -> 0x0a