Encode / Decode numbers
Implement a function to decode Bitcoin-encoded numbers.
Background
In Bitcoin, numbers are often encoded in a special format:
- Numbers are stored in little-endian format (least significant byte first).
- The most significant bit of the last byte indicates the sign (0 for positive, 1 for negative).
- For negative numbers, the absolute value is encoded, and then the result is negated.
For example:
0x01
represents 10x81
represents -10xff00
represents 2550xff80
represents -128
Task
Complete the decodeNum
function in challenges/BitcoinDecoder.js
:
- Implement the logic to decode a Bitcoin-encoded number from a Buffer.
- Handle both positive and negative numbers correctly.
- Return the decoded integer value.
Implementation
Ready to Code?
Choose your preferred language to begin
Click to reveal next hint (0/4)
- Use buffer.readUIntLE() to read the little-endian unsigned integer
- Check the most significant bit of the last byte for the sign
- For negative numbers, you'll need to calculate the two's complement
- Handle edge cases like empty buffers or single-byte values