0

tl;dr: Given x,i = b'', 10, how can I concatenate i onto x, resulting in x == b'\x10'?

I'm trying to encode a number in Python as a varint as a header for a protobuf encoding.

Here's the code I have:

def encode_varint(value):
    buf = b''
    while True:
        byte = value & 0x7f
        value >>= 7
        if value:
            buf += chr(byte | 0x80)
        else:
            buf += chr(byte)
            break
    return buf

However, this fails because I cannot append a string to bytes.

How do I efficiently take an integer value and append it to a binary string?

1
  • The only option I've gotten that 'works' is buf += chr(byte).encode('ascii'), but that does not smell efficient. Commented Dec 2, 2016 at 21:56

1 Answer 1

1
# option 1 (reportedly slower)
buf = b''
buf += bytes([byte])

# option 2 (reportedly faster)
buf = bytearray()
buf.append(byte)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.