Convert a signed decimal to hex encoded with two's complement
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