Converting base 10 number to hex or octal is easy:
>>> oct(100)
'0144'
>>> hex(100)
'0x64'
Is there an *easy* way to convert a number to binary?
def to_base(number, base):
'converts base 10 integer to another base'
number = int(number)
base = int(base)
if base < 2 or base > 36:
raise ValueError, "Base must be between 2 and 36"
if not number:
return 0
symbols = string.digits + string.lowercase[:26]
answer = []
while number:
number, remainder = divmod(number, base)
answer.append(symbols[remainder])
return ''.join(reversed(answer))
Hope this helps,
Michael
---
"I would rather use Java than Perl. And I'd rather be eaten by a
crocodile than use Java." — Trouser
That's way too complicated... Is there any way to convert it to a one-
liner so that I can remember it? Mine is quite ugly:
"".join(str((n/base**i) % base) for i in range(20) if n>=base**i)
[::-1].zfill(1)
Get the gmpy module (note inconsistencies involving octal and hex):
>>> import gmpy
>>> for base in xrange(2,37): print gmpy.digits(255,base)
11111111
100110
3333
2010
1103
513
0377
313
255
212
193
168
143
120
0xff
f0
e3
d8
cf
c3
bd
b2
af
a5
9l
9c
93
8n
8f
87
7v
7o
7h
7a
73
to_base(number, 2) is too complicated?
Howzis?
"".join(map(str,[ int(bool(n & 2**i)) for i in range(20) if n>2**i ]
[::-1]))
Uses:
- integer & to test for bit high or low, returns 2**i
- bool(int) to evaluate boolean value of integers - zero -> False,
nonzero -> True
- int(bool) to convert True->1 and False->0
-- Paul
Howzis?
Still only valid up to 2**20, though.
-- Paul
Wrote this a few moons ago::
dec2bin = lambda x: (dec2bin(x/2) + str(x%2)) if x else ''
Regards,
Stargaming
> On May 17, 4:40 pm, Michael Bentley <mich...@jedimindworks.com> wrote:
> > On May 17, 2007, at 6:33 PM, Lyosha wrote:
> > > Is there an *easy* way to convert a number to binary?
> >
> > def to_base(number, base):
> > [function definition]
> >
> > Hope this helps,
> > Michael
>
> That's way too complicated... Is there any way to convert it to a
> one- liner so that I can remember it?
You put in a module so you don't *have* to remember it.
Then, you use it in this one-liner:
foo = to_base(15, 2)
Carrying a whole lot of one-liners around in your head is a waste of
neurons. Neurons are far more valuable than disk space, screen lines,
or CPU cycles.
--
\ "Quidquid latine dictum sit, altum viditur." ("Whatever is |
`\ said in Latin, sounds profound.") -- Anonymous |
_o__) |
Ben Finney
This is awesome. Exactly what I was looking for. Works for other
bases too.
I guess the reason I couldn't come up with something like this was
being brainwashed that lambda is a no-no.
And python2.5 funky ?: expression comes in handy!
Thanks a lot!
While I agree with this general statement, I think remembering a
particular one-liner to convert a number to a binary is more valuable
to my brain than remembering where I placed the module that contains
this function.
I needed the one-liner not to save disk space or screen lines. It's
to save time, should I need to convert to binary when doing silly
little experiments. I would spend more time getting the module
wherever it is I stored it (and rewriting it if it got lost).
It's fun, too.
Just don't pass it a negative number ;-)
--
Nick Craig-Wood <ni...@craig-wood.com> -- http://www.craig-wood.com/nick
def dec2bin(x): return x and (dec2bin(x/2)+str(x%2)) or ''
does the same job without lambda or Python 2.5 (and note that the
usual warning about a and b or c doesn't apply here as b is
guaranteed to evaluate as true).
--
\S -- si...@chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
"Frankly I have no feelings towards penguins one way or the other"
-- Arthur C. Clarke
her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
regards
Steve
I know the feeling.
In fact, there's a point here that's deep enough to deserve a follow-up.
Various people, including, I think, the timbot, have said that the
distinction of a good high-level language is code NON-re-use; that is,
in the positive aspect, a language like Python is so expressive and
productive that it makes it generally easier to re-use *ideas* than code.