473,385 Members | 1,536 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,385 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 2285
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...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
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: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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...

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.