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

M

mosi

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

John Machin

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

John Machin

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

Daniel

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.
Write your own?

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 :/
 
D

Daniel

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

Bruno Desthuilliers

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
Type "help", "copyright", "credits" or "license" for more information.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
| will be returned instead.

HTH
 
M

mosi

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.


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.

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

Neil Cerutti

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:

but not:

The % format operator can do hex and octal, I believe.
 
D

Duncan Booth

John Machin said:
Here's a sketch; I'll leave you to fill in the details -- you may wish
to guard against interesting input like b < 2.
... 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])
 
W

Wildemar Wildenburger

Bruno said:
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
Type "help", "copyright", "credits" or "license" for more information.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
 
K

Karthik Gurusamy

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
Type "help", "copyright", "credits" or "license" for more information.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
| will be returned instead.

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
 
D

Daniel

Bruno said:
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
Type "help", "copyright", "credits" or "license" for more information.
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?
 
M

mensanator

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

Dan Bishop

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

Bruno Desthuilliers

Karthik Gurusamy a écrit :
(snip)
While it's interesting to know we can go from binary to int, the OP
wanted the other way.

Please reread more carefully the OP's question and code snippet (which
are just above).
 

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

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top