Skip to content

Instantly share code, notes, and snippets.

@ar45
Last active November 26, 2019 00:41
Show Gist options
  • Save ar45/38db0f7bb12ba50b1bd8bb17ae2533de to your computer and use it in GitHub Desktop.
Save ar45/38db0f7bb12ba50b1bd8bb17ae2533de to your computer and use it in GitHub Desktop.
Python 2s Compliment Binary Representation
def twosComp(val, bitlen=None):
if bitlen is None:
bitlen = int(val).bit_length()
val &= ( 2 << bitlen - 1 ) - 1
return '{{:0{bitlen}b}}'.format(bitlen=bitlen).format(val)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment