summaryrefslogtreecommitdiff
path: root/numpy/core/numeric.py
diff options
context:
space:
mode:
authorcookedm <cookedm@localhost>2007-04-02 12:06:06 +0000
committercookedm <cookedm@localhost>2007-04-02 12:06:06 +0000
commitf11fdaee8baeb00fc2a7156cda67c8b0d1eb54ae (patch)
treecfb287d8a2079a4564a17c585a276776f626df89 /numpy/core/numeric.py
parent5c8f992c6ff487f0b5c97cb80ad0706473d05074 (diff)
downloadnumpy-f11fdaee8baeb00fc2a7156cda67c8b0d1eb54ae.tar.gz
binary_repr handles negative numbers now, and takes an optional width argument.
base_repr raise ValueError if the number is negative or base > 36
Diffstat (limited to 'numpy/core/numeric.py')
-rw-r--r--numpy/core/numeric.py41
1 files changed, 28 insertions, 13 deletions
diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py
index 6ca47a87b..f98ca9af0 100644
--- a/numpy/core/numeric.py
+++ b/numpy/core/numeric.py
@@ -546,29 +546,44 @@ _lkup = {
'F':'1111',
'L':''}
-def binary_repr(num):
+def binary_repr(num, width=None):
"""Return the binary representation of the input number as a string.
This is equivalent to using base_repr with base 2, but about 25x
faster.
+
+ For negative numbers, if width is not given, a - sign is added to the
+ front. If width is given, the two's complement of the number is
+ returned, with respect to that width.
"""
- ostr = hex(num)
- bin = ''
- for ch in ostr[2:]:
- bin += _lkup[ch]
- if '1' in bin:
- ind = 0
- while bin[ind] == '0':
- ind += 1
- return bin[ind:]
- else:
+ sign = ''
+ if num < 0:
+ if width is None:
+ sign = '-'
+ num = -num
+ else:
+ # replace num with its 2-complement
+ num = 2**width + num
+ elif num == 0:
return '0'
+ ostr = hex(num)
+ bin = ''.join([_lkup[ch] for ch in ostr[2:]])
+ bin = bin.lstrip('0')
+ if width is not None:
+ bin = bin.zfill(width)
+ return sign + bin
def base_repr (number, base=2, padding=0):
- """Return the representation of a number in any given base.
+ """Return the representation of a number in the given base.
+
+ Base can't be larger than 36.
"""
- chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+ if number < 0:
+ raise ValueError("negative numbers not handled in base_repr")
+ if base > 36:
+ raise ValueError("bases greater than 36 not handled in base_repr")
+ chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
import math
lnb = math.log(base)
res = padding*chars[0]