(b: Buffer, width?: number)
| 112 | * @returns - a deserialized bigint |
| 113 | */ |
| 114 | export function parseSignedInt(b: Buffer, width?: number) { |
| 115 | const buf = Buffer.from(b); |
| 116 | |
| 117 | // We get the last (width / 8) bytes where width = bits of type (i64, i32 etc) |
| 118 | const slicedBuf = width !== undefined ? buf.subarray(-(width / 8)) : buf; |
| 119 | |
| 120 | // Then manually deserialize with 2's complement, with the process as follows: |
| 121 | |
| 122 | // If our most significant bit is high... |
| 123 | if (0x80 & slicedBuf.subarray(0, 1).readUInt8()) { |
| 124 | // We flip the bits |
| 125 | for (let i = 0; i < slicedBuf.length; i++) { |
| 126 | slicedBuf[i] = ~slicedBuf[i]; |
| 127 | } |
| 128 | |
| 129 | // Add one, then negate it |
| 130 | return -(BigInt(`0x${slicedBuf.toString('hex')}`) + 1n); |
| 131 | } |
| 132 | |
| 133 | // ...otherwise we just return our positive int |
| 134 | return BigInt(`0x${slicedBuf.toString('hex')}`); |
| 135 | } |
no test coverage detected