const negativeHexTestPattern = /^[89ABCDEF]/i /* parse signed 2's complement hex string to number */ hexToTwosComplement(hex) { let result = parseInt(hex, 16) // Check if high bit is set. if (negativeHexTestPattern.test(hex)) { // Negative number const subtrahend = (2 ** (hex.length * 4)) result -= subtrahend } return result } /* parse packed binary-coded decimal (BCD) format where unused * trailing digits (4-bits) are filled with all ones (1111). */ hexBCDToString(hex) { let decoded = '' for (let i = 0; i < hex.length; i++) { if ((parseInt(hex[i],16) & 0x0F) !== 0x0F) { decoded += hex[i] } else { break } } return decoded }

Here's a few test cases to demonstrate.

it('converts positive hex values to twos complement', () => { const val = new Processor().hexToTwosComplement('13f6b4eb') chai.expect(val).to.equal(334935275) }) it('converts negative hex values to twos complement', () => { const val = new Processor().hexToTwosComplement('ec094b15') chai.expect(val).to.equal(-334935275) }) it('converts negative 2 byte hex values to twos complement', () => { const val = new Processor().hexToTwosComplement('ffae') chai.expect(val).to.equal(-82) })