Compact Target
Compact Target (nBits)
Implement this pack's unsigned teaching variant of a 4-byte compact target:
[exponent (1 byte)] [mantissa (3 bytes)]
The target is:
T = mantissa * 256^(exponent-3)
Functions
func CompactToTarget(bits uint32) *big.Int
func TargetToCompact(target *big.Int) uint32
Rules
- Use unsigned arithmetic: all low 24 bits belong to the mantissa, including bit 23. Do not interpret that bit as a sign or clear it.
- For exponent <= 3, shift the mantissa right by
8*(3-exponent); otherwise shift it left by8*(exponent-3). Right shifts truncate. - If
target == 0,TargetToCompactshould return0. TargetToCompactmust produce the canonical encoding:- Let
size = len(target.Bytes()). - For size <= 3, shift the target left by
8*(3-size)to form the mantissa. Otherwise retain its first 3 big-endian bytes. - If the first mantissa byte has the high bit set (
>= 0x80), shift the mantissa right by 8 and incrementsize.
- Let
Notes
- You can use
math/bigfor big integers. - Encoder inputs are nonnegative targets of at most 256 bits; nil is treated
as zero. All uint32 compact inputs can be decoded with
math/big. - Encoding can discard low bytes:
0x12345678becomes0x04123456, whose decoded target is0x12345600. - This unsigned variant does not implement Bitcoin's signed compact-target semantics or network validity rules.
- Treat the hash as a big-endian integer when comparing against targets.
Run tests to see results
No issues detected