Skip to content

Instantly share code, notes, and snippets.

@mdwhatcott mdwhatcott/
Last active Feb 23, 2019

What would you like to do?
Chunks the bit groupings in bytes if the specified length is divisible by 8.
def main():
print ' 42 in 32 bits:', bits(42, 32)
print '-42 in 32 bits:', bits(-42, 32)
print '-42 in 20 bits:', bits(-42, 20)
def bits(number, size_in_bits):
The bin() function is *REALLY* unhelpful when working with negative numbers.
It outputs the binary representation of the positive version of that number
with a '-' at the beginning. Woop-di-do. Here's how to derive the two's-
complement binary of a negative number:
complement(bin(+n - 1))
`complement` is a function that flips each bit. `+n` is the negative number
made positive.
if number < 0:
value = compliment(bin(abs(number) - 1)[2:]).rjust(size_in_bits, '1')
value = bin(number)[2:].rjust(size_in_bits, '0')
if not size_in_bits % 8:
return ' '.join(chunks(value, 8))
return value
def chunks(l, n):
Yield successive n-sized chunks from l.
for i in xrange(0, len(l), n):
yield l[i:i+n]
def compliment(value):
return ''.join(COMPLEMENT[x] for x in value)
COMPLEMENT = {'1': '0', '0': '1'}
if __name__ == '__main__':
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.