Skip to content

Instantly share code, notes, and snippets.

@wbond
Created January 26, 2017 19:49
Show Gist options
  • Save wbond/6807567405dd659f234a9e778ea7a4dd to your computer and use it in GitHub Desktop.
Save wbond/6807567405dd659f234a9e778ea7a4dd to your computer and use it in GitHub Desktop.
if signed:
if value < 0:
bits_required = abs(value + 1).bit_length()
else:
bits_required = value.bit_length()
if bits_required % 8 == 0:
bits_required += 1
else:
bits_required = value.bit_length()
width = math.ceil(bits_required / 8) or 1
return value.to_bytes(width, byteorder='big', signed=signed)
@ofek
Copy link

ofek commented Jan 26, 2017

I think it could be simplified to:

bits_required = value.bit_length()

if signed:
    if value < 0:
        bits_required = abs(value + 1).bit_length()
    if not bits_required % 8:
        bits_required += 1

width = (bits_required + 7) // 8 or 1
return value.to_bytes(width, byteorder='big', signed=signed)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment