mirror of
https://github.com/bitcoin/bitcoin.git
synced 2025-12-02 16:59:44 +01:00
Simplify bn2vch using int.to_bytes
This commit is contained in:
committed by
Pieter Wuille
parent
a421e0a22f
commit
a3ad6459b7
@@ -27,38 +27,14 @@ def hash160(s):
|
|||||||
|
|
||||||
def bn2vch(v):
|
def bn2vch(v):
|
||||||
"""Convert number to bitcoin-specific little endian format."""
|
"""Convert number to bitcoin-specific little endian format."""
|
||||||
# The top bit is used to indicate the sign of the number. If there
|
# We need v.bit_length() bits, plus a sign bit for every nonzero number.
|
||||||
# isn't a spare bit in the bit length, add an extension byte.
|
n_bits = v.bit_length() + (v != 0)
|
||||||
have_ext = False
|
# The number of bytes for that is:
|
||||||
ext = bytearray()
|
n_bytes = (n_bits + 7) // 8
|
||||||
if v.bit_length() > 0:
|
# Convert number to absolute value + sign in top bit.
|
||||||
have_ext = (v.bit_length() & 0x07) == 0
|
encoded_v = 0 if v == 0 else abs(v) | ((v < 0) << (n_bytes * 8 - 1))
|
||||||
ext.append(0)
|
# Serialize to bytes
|
||||||
|
return encoded_v.to_bytes(n_bytes, 'little')
|
||||||
# Is the number negative?
|
|
||||||
neg = False
|
|
||||||
if v < 0:
|
|
||||||
neg = True
|
|
||||||
v = -v
|
|
||||||
|
|
||||||
# Convert the int to bytes
|
|
||||||
v_bin = bytearray()
|
|
||||||
bytes_len = (v.bit_length() + 7) // 8
|
|
||||||
for i in range(bytes_len, 0, -1):
|
|
||||||
v_bin.append((v >> ((i - 1) * 8)) & 0xff)
|
|
||||||
|
|
||||||
# Add the sign bit if necessary
|
|
||||||
if neg:
|
|
||||||
if have_ext:
|
|
||||||
ext[0] |= 0x80
|
|
||||||
else:
|
|
||||||
v_bin[0] |= 0x80
|
|
||||||
|
|
||||||
v_bytes = ext + v_bin
|
|
||||||
# Reverse bytes ordering for LE
|
|
||||||
v_bytes.reverse()
|
|
||||||
|
|
||||||
return bytes(v_bytes)
|
|
||||||
|
|
||||||
_opcode_instances = []
|
_opcode_instances = []
|
||||||
class CScriptOp(int):
|
class CScriptOp(int):
|
||||||
|
|||||||
Reference in New Issue
Block a user