Skip to content

Instantly share code, notes, and snippets.

@cuadue
Created February 3, 2012 20:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cuadue/1732435 to your computer and use it in GitHub Desktop.
Save cuadue/1732435 to your computer and use it in GitHub Desktop.
Explode a number into hex and binary representations
#!/usr/bin/python
''' Formats a number into its hex and binary representations. Possibly useful
for manipulating bit masks and writing assembly.
>>> hd(0xfdff)
65023
0x f d f f
0b 1111 1101 1111 1111
'''
def hd(n):
print ' %d' % n
h, b = [], []
while n > 0:
_n = 0xf & n
h.append('{0:<4x}'.format(_n))
b.append('{0:04b}'.format(_n))
n = n >> 4
h.reverse()
b.reverse()
print '0x ' + ' '.join(h)
print '0b ' + ' '.join(b)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment