1 "Collection of tools for displaying bit representation of numbers." ""
4 def binary(n
, width
=None):
6 Return a list of (0|1)'s for the binary representation of n where n >= 0.
7 If you specify a width, it must be > 0, otherwise it is ignored. The list
8 could be padded with 0 bits if width is specified.
11 if width
and width
<= 0:
14 l
.append(1 if n
& 1 else 0)
18 for i
in range(width
- len(l
)):
25 def twos_complement(n
, width
):
27 Return a list of (0|1)'s for the binary representation of a width-bit two's
28 complement numeral system of an integer n which may be negative.
30 val
= 2 ** (width
- 1)
34 # It is safe to represent n with width-bits.
35 return binary(n
, width
)
40 # It is safe to represent n (a negative int) with width-bits.
41 return binary(val
* 2 - abs(n
))
44 # print binary(0xABCD)
45 # [1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1]
46 # print binary(0x1F, 8)
47 # [0, 0, 0, 1, 1, 1, 1, 1]
48 # print twos_complement(-5, 4)
50 # print twos_complement(7, 4)
54 # print twos_complement(-5, 64)
55 # [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]
59 """Helper function returning a list describing the bit positions.
60 Bit positions greater than 99 are truncated to 2 digits, for example,
61 100 -> 00 and 127 -> 27."""
62 return ["{0:2}".format(i
)[-2:] for i
in reversed(range(width
))]
65 def utob(debugger
, command_line
, result
, dict):
66 """Convert the unsigned integer to print its binary representation.
67 args[0] (mandatory) is the unsigned integer to be converted
68 args[1] (optional) is the bit width of the binary representation
69 args[2] (optional) if specified, turns on verbose printing"""
70 args
= command_line
.split()
75 width
= int(args
[1], 0)
87 bits
= binary(n
, width
)
89 print("insufficient width value: %d" % width
)
91 if verbose
and width
> 0:
92 pos
= positions(width
)
93 print(" " + " ".join(pos
))
94 print(" %s" % str(bits
))
97 def itob(debugger
, command_line
, result
, dict):
98 """Convert the integer to print its two's complement representation.
99 args[0] (mandatory) is the integer to be converted
100 args[1] (mandatory) is the bit width of the two's complement representation
101 args[2] (optional) if specified, turns on verbose printing"""
102 args
= command_line
.split()
105 width
= int(args
[1], 0)
117 bits
= twos_complement(n
, width
)
119 print("insufficient width value: %d" % width
)
121 if verbose
and width
> 0:
122 pos
= positions(width
)
123 print(" " + " ".join(pos
))
124 print(" %s" % str(bits
))