Start your career in bitcoin open source — ₿OSS

APPLY TODAY

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 1
  • 0x81 represents -1
  • 0xff00 represents 255
  • 0xff80 represents -128

Task

Complete the decodeNum function in challenges/BitcoinDecoder.js:

  1. Implement the logic to decode a Bitcoin-encoded number from a Buffer.
  2. Handle both positive and negative numbers correctly.
  3. Return the decoded integer value.

Implementation

P2PK ScriptPubKey Decoder Exercise
export function decodeNum(buffer) {
    // TODO: Implement the decoding logic here
    // Remember to handle both positive and negative numbers
    // Return the decoded integer value
}

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
Suggest Edits