473,387 Members | 1,700 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,387 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 8310

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
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

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.