# "number-in-base" ``oneliner''

Bengt Richter bokr at oz.net
Sat Oct 30 09:48:34 CEST 2004

```On Sat, 30 Oct 2004 06:07:23 GMT, bokr at oz.net (Bengt Richter) wrote:
[...]
>Maybe something useful in this? Not very tested (and not terribly clear either ;-)
>
> >>> def number_in_base(x, N, digits):
> ...     return x==0 and digits[0] or '-'[:x<0] + ''.join([d for d in iter(
> ...                 lambda qr=[abs(x),0]:qr[0] and (
> ...                     qr.__setslice__(0,2,divmod(qr[0],N)) or digits[qr[1]])
> ...                 , 0)][::-1])
> ...

Alternatively, a little more compactly (though I feel guilty about the -1 ;-):

>>> def number_in_base(x, N=10, digits='0123456789ABCDEF'):
...     return '-'[:x<0] + ''.join(list(iter(lambda qr=[abs(x),-1]: (qr[0] or qr[1]<0) and (
...         qr.__setslice__(0,2,divmod(qr[0],N)) or digits[qr[1]]), False))[::-1])
...
>>> number_in_base(126,2,'01')
'1111110'
>>> number_in_base( 126, 8,'01234567')
'176'
>>> number_in_base(-126, 8,'01234567')
'-176'
>>> number_in_base(  -1, 2,'01234567')
'-1'
>>> number_in_base(   1, 2,'01234567')
'1'
>>> number_in_base(   0, 2,'01234567')
'0'

Regards,
Bengt Richter

```