1 "Collection of tools for displaying bit representation of numbers."""
3 def binary(n, width=None):
5 Return a list of (0|1)'s for the binary representation of n where n >= 0.
6 If you specify a width, it must be > 0, otherwise it is ignored. The list
7 could be padded with 0 bits if width is specified.
10 if width and width <= 0:
13 l.append(1 if n & 1 else 0)
17 for i in range(width - len(l)):
24 def twos_complement(n, width):
26 Return a list of (0|1)'s for the binary representation of a width-bit two's
27 complement numeral system of an integer n which may be negative.
33 # It is safe to represent n with width-bits.
34 return binary(n, width)
39 # It is safe to represent n (a negative int) with width-bits.
40 return binary(val * 2 - abs(n))
42 # print binary(0xABCD)
43 # [1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1]
44 # print binary(0x1F, 8)
45 # [0, 0, 0, 1, 1, 1, 1, 1]
46 # print twos_complement(-5, 4)
48 # print twos_complement(7, 4)
52 # print twos_complement(-5, 64)
53 # [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1]
57 """Helper function returning a list describing the bit positions.
58 Bit positions greater than 99 are truncated to 2 digits, for example,
59 100 -> 00 and 127 -> 27."""
60 return ['{0:2}'.format(i)[-2:] for i in reversed(range(width))]
63 def utob(debugger, command_line, result, dict):
64 """Convert the unsigned integer to print its binary representation.
65 args[0] (mandatory) is the unsigned integer to be converted
66 args[1] (optional) is the bit width of the binary representation
67 args[2] (optional) if specified, turns on verbose printing"""
68 args = command_line.split()
73 width = int(args[1], 0)
85 bits = binary(n, width)
87 print("insufficient width value
: %d" % width)
89 if verbose and width > 0:
90 pos = positions(width)
91 print(' ' + ' '.join(pos))
92 print(' %s' % str(bits))
95 def itob(debugger, command_line, result, dict):
96 """Convert the integer to print its two's complement representation.
97 args[0] (mandatory) is the integer to be converted
98 args[1] (mandatory) is the bit width of the two's complement representation
99 args[2] (optional) if specified, turns on verbose printing"""
100 args = command_line.split()
103 width = int(args[1], 0)
115 bits = twos_complement(n, width)
117 print("insufficient width value
: %d" % width)
119 if verbose and width > 0:
120 pos = positions(width)
121 print(' ' + ' '.join(pos))
122 print(' %s' % str(bits))