Created
January 26, 2017 19:49
-
-
Save wbond/6807567405dd659f234a9e778ea7a4dd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think it could be simplified to: