Created
February 3, 2012 20:50
-
-
Save cuadue/1732435 to your computer and use it in GitHub Desktop.
Explode a number into hex and binary representations
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
#!/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