473,322 Members | 1,409 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

How to convert a number to binary?

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?

May 17 '07 #1
15 8303

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

---
"I would rather use Java than Perl. And I'd rather be eaten by a
crocodile than use Java." — Trouser
May 17 '07 #2
On May 17, 4:40 pm, Michael Bentley <mich...@jedimindworks.comwrote:
On May 17, 2007, at 6:33 PM, Lyosha wrote:
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)

May 17 '07 #3
On May 17, 6:45 pm, Lyosha <lyos...@gmail.comwrote:
On May 17, 4:40 pm, Michael Bentley <mich...@jedimindworks.comwrote:


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

May 18 '07 #4

On May 17, 2007, at 6:45 PM, Lyosha wrote:
On May 17, 4:40 pm, Michael Bentley <mich...@jedimindworks.comwrote:
>On May 17, 2007, at 6:33 PM, Lyosha wrote:
>>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?
May 18 '07 #5
On May 17, 6:45 pm, Lyosha <lyos...@gmail.comwrote:
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

May 18 '07 #6
On May 17, 6:45 pm, Lyosha <lyos...@gmail.comwrote:
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

May 18 '07 #7

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

May 18 '07 #8
Lyosha schrieb:
On May 17, 4:40 pm, Michael Bentley <mich...@jedimindworks.comwrote:
>>On May 17, 2007, at 6:33 PM, Lyosha wrote:

>>>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
May 18 '07 #9
Lyosha <ly*****@gmail.comwrites:
On May 17, 4:40 pm, Michael Bentley <mich...@jedimindworks.comwrote:
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
May 18 '07 #10
On May 17, 11:04 pm, Stargaming <stargam...@gmail.comwrote:
[...]
>>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!

May 18 '07 #11
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.

May 18 '07 #12
Lyosha <ly*****@gmail.comwrote:
On May 17, 11:04 pm, Stargaming <stargam...@gmail.comwrote:
[...]
>>>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
May 18 '07 #13
Lyosha <ly*****@gmail.comwrote:
>On May 17, 11:04 pm, Stargaming <stargam...@gmail.comwrote:
> 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
May 18 '07 #14
Lyosha wrote:
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.
Id use the "silly little module" even for experiments. Most Python
programmers keep a directory full of such "stock" modules.

regards
Steve

May 18 '07 #15
In article <11*********************@l77g2000hsb.googlegroups. com>,
Lyosha <ly*****@gmail.comwrote:
May 20 '07 #16

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: ferran | last post by:
Hi, does anybody know how to convert in C++ from base 10 to any other base without loosing the decimal part of the actual value? I came up with this algorithm to convert from decimal to any base...
13
by: Hako | last post by:
I try this command: >>> import string >>> string.atoi('78',16) 120 this is 120 not 4E. Someone can tell me how to convert a decimal number to hex number? Can print A, B, C,DEF. Thank you.
7
by: Golan | last post by:
Hi, I need to convert a Binary value to Decimal. I've been told that the value is an unsigned one. How can I do this? I use memcpy into an unsigned char variable, but when I print the value I got...
7
by: whatluo | last post by:
Hi, all I'm now working on a program which will convert dec number to hex and oct and bin respectively, I've checked the clc but with no luck, so can anybody give me a hit how to make this done...
6
by: MrKrich | last post by:
I want to convert Hexadecimal or normal integer to Binary. Does VB.Net has function to do that? I only found Hex function that convert normal integer to Hexadecimal.
3
by: bussiere maillist | last post by:
i've got a very long string and i wanted to convert it in binary like string = """Monty Python, or The Pythons, is the collective name of the creators of Monty Python's Flying Circus, a British...
7
by: elliotng.ee | last post by:
I have a text file that contains a header 32-bit binary. For example, the text file could be: %%This is the input text %%test.txt Date: Tue Dec 26 14:03:35 2006...
28
by: FAQ server | last post by:
----------------------------------------------------------------------- FAQ Topic - How do I convert a Number into a String with exactly 2 decimal places?...
9
by: Leo jay | last post by:
i'd like to implement a class template to convert binary numbers to decimal at compile time. and my test cases are: BOOST_STATIC_ASSERT((bin<1111,1111,1111,1111>::value == 65535));...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.