Permalink
Switch branches/tags
Nothing to show
Find file
Fetching contributors…
Cannot retrieve contributors at this time
executable file 126 lines (103 sloc) 3.14 KB
#!/usr/bin/env python
'''
bitbanger OPTIONS WORD
bitbanger OPTIONS POS [POS]...
POS is a bit position, WORD is a base 16 integer prefixed with 0x in
the byte order of this host.
Example:
> bb 1 2 3 4
> bb 0x1e
'''
__version__ = "0.3"
__date__ = "2010-02-07"
__author__ = "Justin Chouinard <jvc@jvic.net>"
__copyright__ = "Copyright 2010, Justin Chouinard"
__license__ = "MIT"
import sys
BYTE_ORDER_MSG="The byte order of this host is %s endian." % (sys.byteorder)
def get_bit_list(word_size, byte_list = None, word = 0):
'''Return a list() of int()s set to 0 or 1.
'''
bits = []
if byte_list:
for byte in byte_list:
for offset in range(8):
bits.append((1 << int(offset)) & int(byte))
elif word:
for bit in range(word_size):
bits.append((1 << int(bit)) & int(word))
return bits
def get_byte_list(word, word_size):
'''Return a list() of bytes.
'''
bytes = []
for byte in range(word_size / 8):
val = 0xff & (int(word) >> (8 * byte))
bytes.append(val)
return bytes
def print_bit_list(bit_list):
'''Print a list() of bits. Traverse backwards so it reads properly
with the high bit on the LHS.
'''
print "Bin: ",
pos = len(bit_list) - 1
while pos > -1:
bit = 1 if bit_list[pos] else 0
print bit,
if pos % 32 == 0:
print
print ' ',
elif pos % 8 == 0:
print ' ',
pos -= 1
print
print "Set: ",
setbits = []
pos = 0
for item in bit_list:
if item:
setbits.append(str(pos))
pos += 1
print ' '.join(setbits),
print ' (%d bits set)' % len(setbits)
def print_byte_list(byte_list):
'''Print a list() of bytes. Traverse backwards so it reads properly
with the high bit on the LHS.
'''
index = len(byte_list) - 1
while index > -1:
print "%02x" % byte_list[index],
index -= 1
print
def main(word, options):
if options.word_size == 64:
print " word: 0x%016x ->" % word,
else:
print " word: 0x%08x ->" % word,
byte_list = get_byte_list(word, options.word_size)
bit_list = get_bit_list(options.word_size, byte_list=byte_list)
print_byte_list(byte_list)
print_bit_list(bit_list)
def to_hex_str(input):
return "%02x" % input
print " reversed: 0x%s ->" % ''.join(map(to_hex_str, byte_list)),
byte_list.reverse()
print_byte_list(byte_list)
if __name__ == '__main__':
from optparse import OptionParser
parser = OptionParser(usage=__doc__ + BYTE_ORDER_MSG)
parser.add_option("-s", "--size", dest="word_size", type="int", default=32,
help="Set word size to SIZE bits", metavar="SIZE")
(options, args) = parser.parse_args()
word = 0
if args[0].startswith('0x'):
word = int(args[0], 16)
else:
# user passed in enabled bits, build generic word
for arg in args:
for arg in arg.split(","):
if len(arg) > 0:
word |= (1 << (int(arg)))
if word >= 0xffffffff:
options.word_size = 64
main(word, options)