Search code examples
javascriptbytebit

How to convert one byte (8 bit) to signed integer in JavaScript?


I need to convert one byte into java script signed integer. I have checked this link which converts 2 bytes , but how could I downgrade and convert only one byte?

for example 0x0A would be 10, how about 0xD4?


Solution

  • I came up with this solution:

    function convertToSignedInt(signedByte) {
        var sign = signedByte & (1 << 7);
        return (signedByte & 0x7f) * (sign !== 0 ? -1 : 1);
    }
    

    Hope it could save others some time. convertToSignedInt(0x81) // returns -1