Example #1
0
def integer_bit_length_word_aligned(num):
  """
  Number of bits needed to represent a integer excluding any prefix
  0 bits.

  :param num:
      Integer value. If num is 0, returns 0. Only the absolute value of the
      number is considered. Therefore, signed integers will be abs(num)
      before the number's bit length is determined.
  :returns:
      Returns the number of bits in the integer.
  """
  # Do not change this to `not num` otherwise a TypeError will not
  # be raised when `None` is passed in as a value.
  if num == 0:
    return 0
  if num < 0:
    num = -num
  if num > 0x80:
    raw_bytes = _integer_raw_bytes_without_leading(num)
    first_byte = builtins.byte_ord(raw_bytes[0])
    bits = 0
    while first_byte >> bits:
      bits += 1
    return ((len(raw_bytes) - 1) * 8) + bits
  else:
    bits = 0
    while num >> bits:
      bits += 1
    return bits
Example #2
0
def b58encode_bitcoin(v):
  """ encode v, which is a string of bytes, to base58.
  """

  long_value = 0
  for i, c in enumerate(v[::-1]):
    long_value += (256 ** i) * byte_ord(c)

  result = EMPTY_BYTE
  while long_value >= BASE:
    div, mod = divmod(long_value, BASE)
    result = _chr(ALPHABET[mod]) + result
    long_value = div
  result = _chr(ALPHABET[long_value]) + result

  # Bitcoin does a little leading-zero-compression:
  # leading 0-bytes in the input become leading-1s
  nPad = 0
  for c in v:
    if c == ZERO_BYTE: nPad += 1
    else: break

  return (_chr(ALPHABET[0]) * nPad) + result
Example #3
0
def b58encode_bitcoin(v):
    """ encode v, which is a string of bytes, to base58.
  """

    long_value = 0
    for i, c in enumerate(v[::-1]):
        long_value += (256**i) * builtins.byte_ord(c)

    result = EMPTY_BYTE
    while long_value >= BASE:
        div, mod = divmod(long_value, BASE)
        result = _chr(ALPHABET[mod]) + result
        long_value = div
    result = _chr(ALPHABET[long_value]) + result

    # Bitcoin does a little leading-zero-compression:
    # leading 0-bytes in the input become leading-1s
    nPad = 0
    for c in v:
        if c == ZERO_BYTE: nPad += 1
        else: break

    return (_chr(ALPHABET[0]) * nPad) + result