Skip to content

Instantly share code, notes, and snippets.

@keitaoouchi
Created April 3, 2012 04:30
Show Gist options
  • Save keitaoouchi/2289304 to your computer and use it in GitHub Desktop.
Save keitaoouchi/2289304 to your computer and use it in GitHub Desktop.
Convert decimal 2 binary
#!/usr/bin/python
import sys,re
from optparse import OptionParser
def dec2bin(target):
result = []
mask = 1
shift = 0
while mask <= target:
bit = (target & mask) >> shift
result.append(str(bit))
mask <<= 1
shift += 1
return "".join(reversed(result))
def dec2hex(target):
result = []
hexstr = "0123456789ABCDEF"
mask = 15
shift = 0
while mask <= target:
bits = (target & mask) >> shift
result.append(hexstr[bits])
mask <<= 4
shift += 4
bits = (target & mask) >> shift
result.append(hexstr[bits])
return "".join(reversed(result))
def parse_args():
parser = OptionParser()
parser.add_option("-b", "--binary", action = "store_true", default = False)
parser.add_option("-p", "--padding", action = "store_true", default = False)
opt, args = parser.parse_args()
argcheck = True
for arg in args:
if not re.match("^\d*$", arg):
argcheck = False
break
return argcheck, opt, args
if __name__ == "__main__":
argcheck, opt, args = parse_args()
if not argcheck:
print("Error: every arguments must be integer.")
else:
converter = dec2bin if opt.binary else dec2hex
result = [converter(int(arg)) for arg in args]
if opt.padding:
maxlen = max((len(item) for item in result))
a,b = divmod(maxlen, 8)
padding_size = 8 * a if not b else 8 * (a + 1)
for res in result:
print(res.rjust(padding_size, "0"))
else:
for res in result:
print(res)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment