Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

How to convert a number to binary?

52 views
Skip to first unread message

Lyosha

unread,
May 17, 2007, 7:33:52 PM5/17/07
to
Converting binary to base 10 is easy:
>>> int('11111111', 2)
255

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?

Michael Bentley

unread,
May 17, 2007, 7:40:34 PM5/17/07
to pytho...@python.org


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


Lyosha

unread,
May 17, 2007, 7:45:46 PM5/17/07
to

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)

mensa...@aol.com

unread,
May 17, 2007, 7:56:57 PM5/17/07
to
> [::-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

Michael Bentley

unread,
May 17, 2007, 7:58:16 PM5/17/07
to pytho...@python.org

to_base(number, 2) is too complicated?


Paul McGuire

unread,
May 17, 2007, 7:59:04 PM5/17/07
to
On May 17, 6:45 pm, Lyosha <lyos...@gmail.com> wrote:
> 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)
>

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

Paul McGuire

unread,
May 17, 2007, 8:01:29 PM5/17/07
to
On May 17, 6:45 pm, Lyosha <lyos...@gmail.com> wrote:
> 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)
>

Howzis?

Paul McGuire

unread,
May 17, 2007, 8:14:09 PM5/17/07
to

"".join([('0','1')[bool(n & 2**i)] for i in range(20) if n>2**i]
[::-1])

Still only valid up to 2**20, though.

-- Paul

Stargaming

unread,
May 18, 2007, 2:04:23 AM5/18/07
to
Lyosha schrieb:

Wrote this a few moons ago::

dec2bin = lambda x: (dec2bin(x/2) + str(x%2)) if x else ''

Regards,
Stargaming

Ben Finney

unread,
May 18, 2007, 2:10:25 AM5/18/07
to
Lyosha <lyo...@gmail.com> writes:

> 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

Lyosha

unread,
May 18, 2007, 3:45:08 AM5/18/07
to
On May 17, 11:04 pm, Stargaming <stargam...@gmail.com> wrote:
[...]

> >>>Is there an *easy* way to convert a number to binary?
[...]

>
> Wrote this a few moons ago::
>
> dec2bin = lambda x: (dec2bin(x/2) + str(x%2)) if x else ''

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!

Lyosha

unread,
May 18, 2007, 3:52:00 AM5/18/07
to
On May 17, 11:10 pm, Ben Finney <bignose+hates-s...@benfinney.id.au>
wrote:
[...]

> > 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.

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.

Nick Craig-Wood

unread,
May 18, 2007, 5:30:05 AM5/18/07
to
Lyosha <lyo...@gmail.com> wrote:
> On May 17, 11:04 pm, Stargaming <stargam...@gmail.com> wrote:
> [...]
> > >>>Is there an *easy* way to convert a number to binary?
> [...]
> >
> > Wrote this a few moons ago::
> >
> > dec2bin = lambda x: (dec2bin(x/2) + str(x%2)) if x else ''
>
> This is awesome. Exactly what I was looking for. Works for other
> bases too.

Just don't pass it a negative number ;-)

--
Nick Craig-Wood <ni...@craig-wood.com> -- http://www.craig-wood.com/nick

Sion Arrowsmith

unread,
May 18, 2007, 8:49:48 AM5/18/07
to
Lyosha <lyo...@gmail.com> wrote:
>On May 17, 11:04 pm, Stargaming <stargam...@gmail.com> wrote:
>> dec2bin = lambda x: (dec2bin(x/2) + str(x%2)) if x else ''
> [ ... ]

>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!

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

Steve Holden

unread,
May 18, 2007, 4:34:33 PM5/18/07
to pytho...@python.org
Id use the "silly little module" even for experiments. Most Python
programmers keep a directory full of such "stock" modules.

regards
Steve

Cameron Laird

unread,
May 19, 2007, 9:07:32 PM5/19/07
to
In article <1179474720....@l77g2000hsb.googlegroups.com>,
Lyosha <lyo...@gmail.com> wrote:
.
.

.
>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.

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.

0 new messages