468,765 Members | 1,246 Online

# a=0100; print a ; 64 how to reverse this?

Problem:
how to get binary from integer and vice versa?
The simplest way I know is:
a = 0100
a
64

but:
a = 100 (I want binary number)
does not work that way.

a.__hex__ exists
a.__oct__ exists

but where is a.__bin__ ???
What`s the simplest way to do this?
Thank you very much.

Jul 17 '07 #1
14 2055 On Jul 17, 9:09 pm, mosi <skawan...@gmail.comwrote:
Problem:
how to get binary from integer and vice versa?
The simplest way I know is:
a = 0100
a
64

but:
a = 100 (I want binary number)
does not work that way.

a.__hex__ exists
a.__oct__ exists

but where is a.__bin__ ???

What`s the simplest way to do this?
Thank you very much.
Here's a sketch; I'll leave you to fill in the details -- you may wish
to guard against interesting input like b < 2.
>>def anybase(n, b, digits='0123456789abcdef'):
.... tmp = []
.... while n:
.... n, d = divmod(n, b)
.... tmp.append(digits[d])
.... return ''.join(reversed(tmp))
....
>>anybase(1234, 10)
'1234'
>>anybase(7, 2)
'111'
>>[anybase(64, k) for k in range(2, 17)]
['1000000', '2101', '1000', '224', '144', '121', '100', '71', '64',
'59', '54', '4c', '48', '44', '40']
>>>
HTH,
John

Jul 17 '07 #2
On Jul 17, 9:09 pm, mosi <skawan...@gmail.comwrote:
Problem:
how to get binary from integer and vice versa?
The simplest way I know is:
a = 0100
a
64

but:
a = 100 (I want binary number)
does not work that way.

a.__hex__ exists
a.__oct__ exists

but where is a.__bin__ ???

What`s the simplest way to do this?
Thank you very much.
Here's a sketch; I'll leave you to fill in the details -- you may wish
to guard against interesting input like b < 2.
>>def anybase(n, b, digits='0123456789abcdef'):
.... tmp = []
.... while n:
.... n, d = divmod(n, b)
.... tmp.append(digits[d])
.... return ''.join(reversed(tmp))
....
>>anybase(1234, 10)
'1234'
>>anybase(7, 2)
'111'
>>[anybase(64, k) for k in range(2, 17)]
['1000000', '2101', '1000', '224', '144', '121', '100', '71', '64',
'59', '54', '4c', '48', '44', '40']
>>>
HTH,
John

Jul 17 '07 #3
On Tue, 17 Jul 2007 14:09:35 +0300, mosi <sk*******@gmail.comwrote:
>
Problem:
how to get binary from integer and vice versa?
The simplest way I know is:
a = 0100
a
64

but:
a = 100 (I want binary number)
does not work that way.

a.__hex__ exists
a.__oct__ exists

but where is a.__bin__ ???
What`s the simplest way to do this?
Thank you very much.

something like:

def bin(x):
from math import log
bits = (8 if x == 0 else 8*(int(log(x)/log(2))/8+1))
return ''.join([str((x >i) & 1) for i in range(bits)[::-1]])

though that's probably slow :/
--
Using Opera's revolutionary e-mail client: http://www.opera.com/mail/
Jul 17 '07 #4
mosi a écrit :
Problem:
how to get binary from integer and vice versa?
The simplest way I know is:
a = 0100
a
64

but:
a = 100 (I want binary number)
does not work that way.

a.__hex__ exists
a.__oct__ exists

but where is a.__bin__ ???
What`s the simplest way to do this?
bruno@bruno:~\$ python
Python 2.5.1 (r251:54863, May 2 2007, 16:56:35)
[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
>>help(int)
Help on class int in module __builtin__:

class int(object)
| int(x[, base]) -integer
|
| Convert a string or number to an integer, if possible. A floating
point
| argument will be truncated towards zero (this does not include a string
| representation of a floating point number!) When converting a
string, use
| the optional base. It is an error to supply a base when converting a
| non-string. If the argument is outside the integer range a long object
>>a = int('100', 2)
a
4
>>>
HTH
Jul 17 '07 #5
On Tue, 17 Jul 2007 14:09:35 +0300, mosi <sk*******@gmail.comwrote:
>
Problem:
how to get binary from integer and vice versa?
The simplest way I know is:
a = 0100
a
64

Also that is not binary - that is octal, binary would be: '01000000'
(denoted as a string, since 01000000 in octal is actually 262144 in
decimal.
Jul 17 '07 #6
Thank you,
this is great,
I thought that this should be standard in python 2.4 or 2.5 or in some
standard library (math ???)
Didn`t find anything.
On Jul 17, 2:05 pm, John Machin <sjmac...@lexicon.netwrote:
On Jul 17, 9:09 pm, mosi <skawan...@gmail.comwrote:
Problem:
how to get binary from integer and vice versa?
The simplest way I know is:
a = 0100
a
64
but:
a = 100 (I want binary number)
does not work that way.
a.__hex__ exists
a.__oct__ exists
but where is a.__bin__ ???
What`s the simplest way to do this?
Thank you very much.

Here's a sketch; I'll leave you to fill in the details -- you may wish
to guard against interesting input like b < 2.
>def anybase(n, b, digits='0123456789abcdef'):

... tmp = []
... while n:
... n, d = divmod(n, b)
... tmp.append(digits[d])
... return ''.join(reversed(tmp))
...>>anybase(1234, 10)
'1234'
>anybase(7, 2)
'111'
>[anybase(64, k) for k in range(2, 17)]

['1000000', '2101', '1000', '224', '144', '121', '100', '71', '64',
'59', '54', '4c', '48', '44', '40']

HTH,
John

Jul 17 '07 #7
On 2007-07-17, mosi <sk*******@gmail.comwrote:
Thank you,
this is great,
I thought that this should be standard in python 2.4 or 2.5 or in some
standard library (math ???)
Didn`t find anything.
Support is built-in for string representations of numbers in other
than base 10, but conversions to integer is the only support.

You can do:
>>d = int(s, base).
but not:
>>s = str(d, base)
The % format operator can do hex and octal, I believe.

--
Neil Cerutti
Jul 17 '07 #8
John Machin <sj******@lexicon.netwrote:
Here's a sketch; I'll leave you to fill in the details -- you may wish
to guard against interesting input like b < 2.
>>>def anybase(n, b, digits='0123456789abcdef'):
... tmp = []
... while n:
... n, d = divmod(n, b)
... tmp.append(digits[d])
... return ''.join(reversed(tmp))
...
Nice. Here's a one-line version based on your code (with added check for
negative n):

def anybase(n, b, digits='0123456789abcdef'):
return ('-'+anybase(-n,b) if n < 0
else '0' if n==0
else ''.join([digits[d] for (n,d) in iter(lambda:divmod(n,b),
(0,0))])[::-1])

Jul 17 '07 #9
Bruno Desthuilliers wrote:
mosi a écrit :
>Problem:
how to get binary from integer and vice versa?
[snip]
What`s the simplest way to do this?

bruno@bruno:~\$ python
Python 2.5.1 (r251:54863, May 2 2007, 16:56:35)
[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
>>help(int)
Help on class int in module __builtin__:

class int(object)
| int(x[, base]) -integer
:D

After reading the other two replies, this one made me burst with
laughter. Thanks for that.
/W
Jul 17 '07 #10
On Jul 17, 5:35 am, Bruno Desthuilliers <bruno.
42.desthuilli...@wtf.websiteburo.oops.comwrote:
mosi a écrit :
Problem:
how to get binary from integer and vice versa?
The simplest way I know is:
a = 0100
a
64
but:
a = 100 (I want binary number)
does not work that way.
a.__hex__ exists
a.__oct__ exists
but where is a.__bin__ ???
What`s the simplest way to do this?

bruno@bruno:~\$ python
Python 2.5.1 (r251:54863, May 2 2007, 16:56:35)
[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
>>help(int)
Help on class int in module __builtin__:

class int(object)
| int(x[, base]) -integer
|
| Convert a string or number to an integer, if possible. A floating
point
| argument will be truncated towards zero (this does not include a string
| representation of a floating point number!) When converting a
string, use
| the optional base. It is an error to supply a base when converting a
| non-string. If the argument is outside the integer range a long object
>>a = int('100', 2)
>>a
4
>>>

HTH
While it's interesting to know we can go from binary to int, the OP
wanted the other way.

I think it will be a nice enhancement to add to % operator (like %x,
something for binary, %b or %t say) or something like a.__bin__ as
suggested by the OP.

FWIW, gdb has a /t format to print in binary.

(gdb) p 100
\$28 = 100
(gdb) p /x 100
\$29 = 0x64
(gdb) p /t 100
\$30 = 1100100
(gdb)

--Karthik
Jul 17 '07 #11
On Tue, 17 Jul 2007 21:22:03 +0300, Wildemar Wildenburger
<wi******@freakmail.dewrote:
>
Bruno Desthuilliers wrote:
>>Problem:
how to get binary from integer and vice versa?
[snip]
What`s the simplest way to do this?

bruno@bruno:~\$ python
Python 2.5.1 (r251:54863, May 2 2007, 16:56:35)
[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
> >>help(int)
Help on class int in module __builtin__:

class int(object)
| int(x[, base]) -integer

:D

After reading the other two replies, this one made me burst with
laughter. Thanks for that.
Why exactly?
Jul 17 '07 #12
On Jul 17, 7:40 am, mosi <skawan...@gmail.comwrote:
Thank you,
this is great,
I thought that this should be standard in python 2.4 or 2.5 or in some
standard library (math ???)
Didn`t find anything.
You can also look up the gmpy module (not part of standard library).

It contains a lot of functions for use with binary numbers
(there are many others, I'm just showing the ones used for
binary numbers):

DESCRIPTION
gmpy 1.04 - General Multiprecision arithmetic for PYthon:
exposes functionality from the GMP 4 library to Python 2.{2,3,4}.

Allows creation of multiprecision integer (mpz), float (mpf),
and rational (mpq) numbers, conversion between them and to/from
Python numbers/strings, arithmetic, bitwise, and some other
higher-level mathematical operations; also, pretty good-quality
linear-congruential random number generation and shuffling.

mpz has comparable functionality to Python's builtin longs, but
can be faster for some operations (particularly multiplication
and raising-to-power) and has many further useful and speedy
functions (prime testing and generation, factorial, fibonacci,
binary-coefficients, gcd, lcm, square and other roots, ...).

mpf and mpq only offer basic arithmetic abilities, but they
do add the ability to have floating-point numbers ensuring at
least a predefined number of bits' worth of precision (and with
potentially-huge or extremely-tiny magnitudes), as well as
unlimited-precision rationals, with reasonably-fast operations,
which are not built-in features of Python.

FUNCTIONS

digits(...)
digits(x[,base]): returns Python string representing x in the
given base (2 to 36, default 10 if omitted or 0); leading '-'
present if x<0, but no leading '+' if x>=0. x must be an mpz,
or else gets coerced into one.

getbit(...)
getbit(x,n): returns 0 or 1, the bit-value of bit n of x;
n must be an ordinary Python int, >=0; x is an mpz, or else
gets coerced to one.

hamdist(...)
hamdist(x,y): returns the Hamming distance (number of bit-
positions
where the bits differ) between x and y. x and y must be mpz,
or else
get coerced to mpz.

lowbits(...)
lowbits(x,n): returns the n lowest bits of x; n must be an
ordinary Python int, >0; x must be an mpz, or else gets
coerced to one.

numdigits(...)
numdigits(x[,base]): returns length of string representing x
in
the given base (2 to 36, default 10 if omitted or 0); the
value
returned may sometimes be 1 more than necessary; no provision
for any 'sign' characte, nor leading '0' or '0x' decoration,
is made in the returned length. x must be an mpz, or else
gets
coerced into one.

popcount(...)
popcount(x): returns the number of 1-bits set in x; note that
this is 'infinite' if x<0, and in that case, -1 is returned.
x must be an mpz, or else gets coerced to one.

scan0(...)
scan0(x, n=0): returns the bit-index of the first 0-bit of x
(that
is at least n); n must be an ordinary Python int, >=0. If no
more
0-bits are in x at or above bit-index n (which can only happen
for
x<0, notionally extended with infinite 1-bits), None is
returned.
x must be an mpz, or else gets coerced to one.

scan1(...)
scan1(x, n=0): returns the bit-index of the first 1-bit of x
(that
is at least n); n must be an ordinary Python int, >=0. If no
more
1-bits are in x at or above bit-index n (which can only happen
for
x>=0, notionally extended with infinite 0-bits), None is
returned.
x must be an mpz, or else gets coerced to one.

setbit(...)
setbit(x,n,v=1): returns a copy of the value of x, with bit n
set
to value v; n must be an ordinary Python int, >=0; v, 0 or !
=0;
x must be an mpz, or else gets coerced to one.

Jul 18 '07 #13
On Jul 17, 7:40 am, mosi <skawan...@gmail.comwrote:
Thank you,
this is great,
I thought that this should be standard in python 2.4 or 2.5 or in some
standard library (math ???)
Didn`t find anything.
The bin() function is slated to be added to the next version of
Python.

Why there isn't a general itoa() function, I don't know.

Jul 18 '07 #14
Karthik Gurusamy a écrit :
On Jul 17, 5:35 am, Bruno Desthuilliers <bruno.
42.desthuilli...@wtf.websiteburo.oops.comwrote:
>mosi a écrit :
>>Problem:
how to get binary from integer and vice versa?
The simplest way I know is:
a = 0100
a
64
but:
a = 100 (I want binary number)
does not work that way.
a.__hex__ exists
a.__oct__ exists
but where is a.__bin__ ???
What`s the simplest way to do this?
(snip)
> >>a = int('100', 2)
a
4
(snip)
While it's interesting to know we can go from binary to int, the OP
wanted the other way.
 8 posts views Thread by vijay | last post: by 10 posts views Thread by aatish19 | last post: by 11 posts views Thread by A.M | last post: by 6 posts views Thread by raghuveer | last post: by 9 posts views Thread by cniharral | last post: by 12 posts views Thread by nembo kid | last post: by 38 posts views Thread by ssecorp | last post: by 11 posts views Thread by JWest46088 | last post: by reply views Thread by PrototypeChain | last post: by reply views Thread by rvphilip | last post: by reply views Thread by ioana budai | last post: by 1 post views Thread by andreabiancu | last post: by 3 posts views Thread by Zachary1234 | last post: by 1 post views Thread by Geralt96 | last post: by reply views Thread by pocahontas98 | last post: by 3 posts views Thread by skydivetom | last post: by reply views Thread by xarzu | last post: by