How to convert a number to binary?

L

Lyosha

Converting binary to base 10 is easy:255

Converting base 10 number to hex or octal is easy:'0x64'

Is there an *easy* way to convert a number to binary?
 
M

Michael Bentley

Converting binary to base 10 is easy:
255

Converting base 10 number to hex or octal is easy:
'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
 
L

Lyosha

Converting binary to base 10 is easy:

Converting base 10 number to hex or octal is easy:

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

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)
 
M

mensanator

On May 17, 2007, at 6:33 PM, Lyosha wrote:
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

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):

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
 
M

Michael Bentley

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?

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

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)

to_base(number, 2) is too complicated?
 
P

Paul McGuire

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
 
P

Paul McGuire

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
 
P

Paul McGuire

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

Stargaming

Lyosha said:
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?

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


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)

Wrote this a few moons ago::

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

Regards,
Stargaming
 
B

Ben Finney

Lyosha said:
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.
 
L

Lyosha

[...]

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

Lyosha

On May 17, 11:10 pm, Ben Finney <[email protected]>
wrote:
[...]
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.
 
S

Sion Arrowsmith

Lyosha said:
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

Steve Holden

Lyosha said:
On May 17, 11:10 pm, Ben Finney <[email protected]>
wrote:
[...]
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.
Id use the "silly little module" even for experiments. Most Python
programmers keep a directory full of such "stock" modules.

regards
Steve
 
C

Cameron Laird

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top