473,239 Members | 1,467 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,239 software developers and data experts.

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 2276
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.
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 :/
--
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
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
|
| 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.
>>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
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.
/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
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
|
| 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.
>>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:
>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?
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.
Please reread more carefully the OP's question and code snippet (which
are just above).

Jul 18 '07 #15

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

Similar topics

8
by: vijay | last post by:
Hello, As the subject suggests, I need to print the string in the reverse order. I made the following program: # include<stdio.h> struct llnode { char *info;
10
by: aatish19 | last post by:
1: Write a program that asks the user to input an integer value and print it in a reverse order Sample Output Enter any number 65564 Reverse of 65564 is 46556 2: Write a program that takes a...
11
by: A.M | last post by:
Hi, I found print much more flexible that write method. Can I use print instead of file.write method? Thank you,
6
by: raghuveer | last post by:
i want to print my linked list in the reverse order ie..last item first and first item last..this is what i have so far struct linked_list { int number; struct linked_list *next; }; typedef...
9
by: cniharral | last post by:
Hi, I'm interested in printing out coloured lines of my application and I don't know what to use. Can anybody give me an idea?? Regards. Carlos Niharra López
12
by: nembo kid | last post by:
How I (recursive) can reverse and print a string (as simple as possible)? I tried with the following code, but it doesn't work. Thanks in advance to everbody. /* Code starts here */ ...
38
by: ssecorp | last post by:
char* reverse(char* str) { int length = strlen(str); char* acc; int i; for (i=0; i<=length-1; i++){ acc = str; } return acc; }
11
by: JWest46088 | last post by:
I'm having difficulty trying to figure out how to print a text file from a hash table one line at a time. I have the text file read into the hash table and can print the text file all at once, but I...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...

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.