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

How to convert base 10 to base 2?

7,493 views
Skip to first unread message

gian...@gmail.com

unread,
Aug 20, 2012, 3:50:53 AM8/20/12
to
Hi,
as you can argue from the subject, i'm really,really new to python.
What is the best way to achieve that with python? Because the syntax int('30',2) doesn't seem to work!

Benjamin Kaplan

unread,
Aug 20, 2012, 4:04:22 AM8/20/12
to pytho...@python.org
That syntax goes the other way- from a string representing a number in
the given base into an integer (which doesn't have a base, although
it's stored in base 2).

You get the binary by doing bin(x), where x is an integer.

>>> bin(12)
'0b1100'

If you want to go from a string in base-10 to a string in base-2, you
have to do the conversion to integer first.

>>> bin(int('5',10))
'0b101'

Although you don't need to specify the 10 because that's the default.
>>> bin(int('5'))
'0b101'

Mark Lawrence

unread,
Aug 20, 2012, 4:10:25 AM8/20/12
to pytho...@python.org
When you have a problem please cut and paste the exact thing that you
tried with the entire traceback. "Doesn't seem to work" doesn't tell us
a lot. Your OS and Python version is usually needed as well but we
might be able to skip those details in this case :) How much general
programming experience do you have?

--
Cheers.

Mark Lawrence.

lipska the kat

unread,
Aug 20, 2012, 4:26:35 AM8/20/12
to
>>> x = bin(30)[2:]
>>> x
'11110'
>>> int(x, 2)
30
>>>

lipska

--
Lipska the Kat�: Troll hunter, sandbox destroyer
and farscape dreamer of Aeryn Sun

gian...@gmail.com

unread,
Aug 20, 2012, 4:57:43 AM8/20/12
to
Thank you all for the big help!
@Mark Lawrence
Yes, you're definetely right: i should have posted my OS and the version but being a very rough question on syntax i thought it didn't really matter.
I've quite a good general programming experience. I know Java,Visual Basic.NET,Pascal and Mathematica.

Jean-Michel Pichavant

unread,
Aug 20, 2012, 10:52:42 AM8/20/12
to gian...@gmail.com, pytho...@python.org
note that the builtin bin function is not available with python ver < 2.6

def Denary2Binary(n):
'''convert denary integer n to binary string bStr'''
bStr = ''
if n < 0: raise ValueError, "must be a positive integer"
if n == 0: return '0'
while n > 0:
bStr = str(n % 2) + bStr
n = n >> 1
return bStr

JM

(not my function but I can't remember who I stole from)
Message has been deleted

Joel Goldstick

unread,
Aug 20, 2012, 1:57:59 PM8/20/12
to Dennis Lee Bieber, pytho...@python.org
On Mon, Aug 20, 2012 at 1:29 PM, Dennis Lee Bieber
<wlf...@ix.netcom.com> wrote:
> On Mon, 20 Aug 2012 16:52:42 +0200, Jean-Michel Pichavant
> <jeanm...@sequans.com> declaimed the following in
> gmane.comp.python.general:
>
>> note that the builtin bin function is not available with python ver < 2.6
>>
>> def Denary2Binary(n):
>> '''convert denary integer n to binary string bStr'''
>> bStr = ''
>> if n < 0: raise ValueError, "must be a positive integer"
>> if n == 0: return '0'
>> while n > 0:
>> bStr = str(n % 2) + bStr
>> n = n >> 1
>> return bStr
>>
>> JM
>>
>> (not my function but I can't remember who I stole from)
>
> I think I typically have done this by going through a hex
> representation.
>
> H2B_Lookup = { "0" : "0000", "1" : "0001",
> "2" : "0010", "3" : "0011",
> "4" : "0100", "5" : "0101",
> "6" : "0110", "7" : "0111",
> "8" : "1000", "9" : "1001",
> "A" : "1010", "B" : "1011",
> "C" : "1100", "D" : "1101",
> "D" : "1110", "F" : "1111" }
>
> def I2B(i):
> sgn = " "
> if i < 0:
> sgn = "-"
> i = -i
> h = ("%X" % i)
> return sgn + "".join([H2B_Lookup[c] for c in h])
>
>>>> from i2b import I2B
>>>> I2B(10)
> ' 1010'
>>>> I2B(1238)
> ' 010011100110'
>>>> I2B(-6)
> '-0110'
>>>>
> --
> Wulfraed Dennis Lee Bieber AF6VN
> wlf...@ix.netcom.com HTTP://wlfraed.home.netcom.com/
>
> --
> http://mail.python.org/mailman/listinfo/python-list

This may be moving off topic, but since you encode -6 as -0110 I
thought I'd chime in on 'two's complement'

with binary number, you can represent 0 to 255 in a byte, or you can
represent numbers from 127 to -128. To get the negative you
complement each bit (0s to 1s, 1s to 0s), then add one to the result.
So:
3 --> 00000011
~3 -> 111111100
add 1 1
result 111111101

The nice thing about this representation is that arithmetic works just
fine with a mixture of negative and positive numbers.

eg 8 + (-3) ----> 00001000
111111101
gives: 00000101
which is 5!

--
Joel Goldstick

Ian Kelly

unread,
Aug 20, 2012, 2:00:21 PM8/20/12
to Python
I would throw a .lstrip('0') in there to get rid of the ugly leading
zeroes (and also add a special case for i == 0).

Everybody should know the generic algorithm, though:

from itertools import chain

def convert(n, base):
digits = [chr(x) for x in chain(range(ord('0'), ord('9')+1),
range(ord('A'), ord('Z')+1))]
if not 2 <= base <= len(digits):
raise ValueError("invalid base")
output = []
sign = ""
if n < 0:
n = -n
sign = "-"
while n > 0:
n, r = divmod(n, base)
output.append(digits[r])
return sign + ''.join(reversed(output)) or '0'

Ian Kelly

unread,
Aug 20, 2012, 2:10:18 PM8/20/12
to Python
On Mon, Aug 20, 2012 at 11:57 AM, Joel Goldstick
<joel.go...@gmail.com> wrote:
> This may be moving off topic, but since you encode -6 as -0110 I
> thought I'd chime in on 'two's complement'
>
> with binary number, you can represent 0 to 255 in a byte, or you can
> represent numbers from 127 to -128. To get the negative you
> complement each bit (0s to 1s, 1s to 0s), then add one to the result.
> So:
> 3 --> 00000011
> ~3 -> 111111100
> add 1 1
> result 111111101
>
> The nice thing about this representation is that arithmetic works just
> fine with a mixture of negative and positive numbers.
>
> eg 8 + (-3) ----> 00001000
> 111111101
> gives: 00000101
> which is 5!

The main reason to use two's complement is when you need to encode the
negative sign of the number as a bit in a format of fixed width, e.g.
within a byte or word. In a string representation, unless you are
specifically trying to represent computer memory, it is usually better
to just use a minus sign, to be more consistent with how we usually
represent numerals.

Otherwise, note that complement representations are not specific to
binary. For example, with decimal numbers we could use "ten's
complement": individually subtract each digit from 9, and add 1 to the
result. A leading digit between 5 and 9 would be considered negative.

So, for example:
-(042) --> 958
-(958) --> 042

958 + 042 == 000

Cheers,
Ian

Paul Rubin

unread,
Aug 21, 2012, 12:05:45 AM8/21/12
to
Ian Kelly <ian.g...@gmail.com> writes:
> Everybody should know the generic algorithm, though:
> from itertools import chain ...

For n>0, assuming you just want the converted digits and not a string.
String conversion and minus sign for n<0 left as exercise. Note this
returns a generator that you can convert to a list with list(...).

def convert(n, base):
a,b = divmod(n,base)
if a > 0:
for e in convert(a,base):
yield e
yield b

Miki Tebeka

unread,
Aug 21, 2012, 12:23:00 PM8/21/12
to pytho...@python.org
> You get the binary by doing bin(x), where x is an integer.
Note that Python also support binary number literals (prefixed with 0b):
In [1]: 0b101
Out[1]: 5

Miki Tebeka

unread,
Aug 21, 2012, 12:23:00 PM8/21/12
to comp.lan...@googlegroups.com, pytho...@python.org
> You get the binary by doing bin(x), where x is an integer.
0 new messages