Return a string representation of a number in the given base system. Parameters ---------- number : int The value to convert. Positive and negative values are handled. base : int, optional Convert `number` to the `base` number system. The valid range is 2-36,
(number, base=2, padding=0)
| 2050 | |
| 2051 | @set_module('numpy') |
| 2052 | def base_repr(number, base=2, padding=0): |
| 2053 | """ |
| 2054 | Return a string representation of a number in the given base system. |
| 2055 | |
| 2056 | Parameters |
| 2057 | ---------- |
| 2058 | number : int |
| 2059 | The value to convert. Positive and negative values are handled. |
| 2060 | base : int, optional |
| 2061 | Convert `number` to the `base` number system. The valid range is 2-36, |
| 2062 | the default value is 2. |
| 2063 | padding : int, optional |
| 2064 | Number of zeros padded on the left. Default is 0 (no padding). |
| 2065 | |
| 2066 | Returns |
| 2067 | ------- |
| 2068 | out : str |
| 2069 | String representation of `number` in `base` system. |
| 2070 | |
| 2071 | See Also |
| 2072 | -------- |
| 2073 | binary_repr : Faster version of `base_repr` for base 2. |
| 2074 | |
| 2075 | Examples |
| 2076 | -------- |
| 2077 | >>> np.base_repr(5) |
| 2078 | '101' |
| 2079 | >>> np.base_repr(6, 5) |
| 2080 | '11' |
| 2081 | >>> np.base_repr(7, base=5, padding=3) |
| 2082 | '00012' |
| 2083 | |
| 2084 | >>> np.base_repr(10, base=16) |
| 2085 | 'A' |
| 2086 | >>> np.base_repr(32, base=16) |
| 2087 | '20' |
| 2088 | |
| 2089 | """ |
| 2090 | digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' |
| 2091 | if base > len(digits): |
| 2092 | raise ValueError("Bases greater than 36 not handled in base_repr.") |
| 2093 | elif base < 2: |
| 2094 | raise ValueError("Bases less than 2 not handled in base_repr.") |
| 2095 | |
| 2096 | num = abs(number) |
| 2097 | res = [] |
| 2098 | while num: |
| 2099 | res.append(digits[num % base]) |
| 2100 | num //= base |
| 2101 | if padding: |
| 2102 | res.append('0' * padding) |
| 2103 | if number < 0: |
| 2104 | res.append('-') |
| 2105 | return ''.join(reversed(res or '0')) |
| 2106 | |
| 2107 | |
| 2108 | # These are all essentially abbreviations |