Can string formatting be used to convert an integer to its binaryform ?

F

fdu.xiaojf

Hi,

String formatting can be used to converting an integer to its octal or
hexadecimal form:'c7'

But, can string formatting be used to convert an integer to its binary
form ?


Thanks in advance.

xiaojf
 
M

Mirco Wahab

Thus spoke (e-mail address removed) (on 2006-09-28 09:10):
String formatting can be used to converting an integer to its octal or
hexadecimal form:
'c7'

But, can string formatting be used to convert an integer to its binary
form ?

I didn't fell over this problem so far but
I *would* have expected to find something
like a 'pack' operator (as in Perl).

And voilá, there is (even basically identical to Perl):

from struct import *

a = 199
a_bin_str = pack('L', a)



Regards

Mirco
 
G

Gabriel Genellina

a = 199
a_bin_str = pack('L', a)

Notice that the OP was looking for another thing, given the examples.
Perhaps a better wording would have been "how to convert an integer
to its base-2 string representation".


Gabriel Genellina
Softlab SRL





__________________________________________________
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas
 
M

Mirco Wahab

Thus spoke Gabriel Genellina (on 2006-09-28 11:05):
Notice that the OP was looking for another thing, given the examples.
Perhaps a better wording would have been "how to convert an integer
to its base-2 string representation".

Yes, you are right. The OP looks for a
'binary (bit) representation ..."
I admit I didn't find out how to format
a value into a bit string in Python.

In Perl, this would be a no-brainer:

$var = 199;
$str = sprintf "%0*b", 32, $var;

and str would contain 00000000000000000000000011000111
on a intel machine.

But where is the %b in Python?

Regards & Thanks

Mirco
 
F

Frederic Rentsch

Mirco Wahab:


Python doesn't have that. You can convert the number to a hex, and then
map the hex digitds to binary strings using a dictionary, like this:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440528

Bye,
bearophile
Good idea, but shorter with ->
http://cheeseshop.python.org/pypi/SE/2.2 beta
5=0101 6=0110 7=0111 8=1000 9=1001 A=1010 a=1010 B=1011 b=1011 C=1100
c=1100 D=1101 d=1101 E=1110 e=1110 F=1111 f=1111')
'01001001100101100000001011010010'
'00111010110111100110100010110001'


Frederic
 
M

Mirco Wahab

Thus spoke Frederic Rentsch (on 2006-09-28 20:43):
Good idea, but shorter with ->
http://cheeseshop.python.org/pypi/SE/2.2 beta
SE.SE ('se_definition_files/int_to_binary.se') ('%X' % 987654321)
'00111010110111100110100010110001'

I don't really understand here:

- why doesn't have Python such a simple and useful thing as to_binstr(...)
even C++ has one built in,
#include <iostream>
#include <bitset>

int somefunc()
{
int val = 199;
std::cout << std::bitset<32>( val );
...

- why would you favor such complicated solutions
for this (as posted), when you can have this
in one line, e.g.:

def int2bin(num, width=32):
return ''.join(['%c'%(ord('0')+bool((1<<k)&num)) for k in range((width-1),-1,-1)])

(including a string with specifier,this is what I came up with after
looking up some Python docs - maybe you can straighten this a bit ...)

-- but my goggles might be biased,
I don't really emphasize the "Python way" ;-)

Regards and thanks

Mirco
 
M

Marc 'BlackJack' Rintsch

Thus spoke Frederic Rentsch (on 2006-09-28 20:43):

I don't really understand here:

- why doesn't have Python such a simple and useful thing as to_binstr(...)

Maybe simple, but useful? And if you really need this it's simple to
implement or look up in the cook book.
- why would you favor such complicated solutions
for this (as posted), when you can have this
in one line, e.g.:

def int2bin(num, width=32):
return ''.join(['%c'%(ord('0')+bool((1<<k)&num)) for k in range((width-1),-1,-1)])

Yeah, I wonder why not everybody sees the beauty in this cool and
straightforward one liner. ;-)

Ciao,
Marc 'BlackJack' Rintsch
 
M

Mirco Wahab

Thus spoke Marc 'BlackJack' Rintsch (on 2006-09-28 23:38):
def int2bin(num, width=32):
return ''.join(['%c'%(ord('0')+bool((1<<k)&num)) for k in range((width-1),-1,-1)])

Yeah, I wonder why not everybody sees the beauty in this cool and
straightforward one liner. ;-)

Right. I see this is BS, maybe lots of these lines exist already,
one could come up with (sorted by obfuscation, descending):

def int2bin(num, width=32):
# return ''.join( [chr(ord('0')+bool(1<<k & num))for k in range(width-1,-1,-1)] )
# return ''.join( map(lambda k:str(num>>k & 1),range(width-1, -1, -1)) )
# return ''.join( [str(num>>k & 1)for k in range(width-1, -1, -1)] )

But after some thinking, I thought about discussing this one:

def i2b(num, width):
return str(1 & num>>(width-1)) + i2b(num, width-1) if width else ''

which is the shortest ;-)

(Sorry but I'm more or less a newbie, maybe this is BS too ...)

Regards

Mirco
 
M

Mirco Wahab

Thus spoke Fredrik Lundh (on 2006-09-28 23:35):
useful? really? for what?

I don't really know, but according to google,
people often ask exactly for that and there
is no reason at all why one shouldn't expect
to get a /bit string/ from "%b" %.

So if people think it's badly needed, how
couldn't it be *not* useful then? ;-)

It feels to me (as it does sometimes
when diving into Python, to be honest)
simply as a shortcoming, - and the ter-
nary operator included in 2.5 was
imho a huge step forward, next will
be mutable strings and arrays will be
'called arrays' somewhere ... ;-)

(maybe somebody reverses the -v/-V switch too, hey)

Regards

Mirco
 
B

bearophileHUGS

Frederic Rentsch:
Good idea, but shorter with ->
'00111010110111100110100010110001'

Note that your version keeps the leading zeros.
Have you tested the relative speeds too?
(I'll probably have to learn to use SE.)

Bye,
bearophile
 
L

Lawrence D'Oliveiro

"".join([["0", "1"][(1 << i & n) != 0] for i in range(int(math.ceil(math.log(n, 2))) - 1, -1, -1)])

Uh, make that

"".join([["0", "1"][(1 << i & n) != 0] for i in range(int(math.floor(math.log(n, 2))), -1, -1)])

Need to check those corner cases. :)
 
G

Gabriel Genellina

At said:
How about this: (where n is the integer you want to convert):

"".join([["0", "1"][(1 << i & n) != 0] for i in
range(int(math.ceil(math.log(n, 2))) - 1, -1, -1)])

Uhm... so to generate a binary string you have to import the math
module, convert the integer to float, compute a non-standard
logarithm, and then...
What if n<=0?
Too much, don't you think? :)


Gabriel Genellina
Softlab SRL





__________________________________________________
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas
 
G

George Sakkis

Gabriel said:
At said:
How about this: (where n is the integer you want to convert):

"".join([["0", "1"][(1 << i & n) != 0] for i in
range(int(math.ceil(math.log(n, 2))) - 1, -1, -1)])

Uhm... so to generate a binary string you have to import the math
module, convert the integer to float, compute a non-standard
logarithm, and then...
What if n<=0?
Too much, don't you think? :)

Having recently discovered the joy of obfuscated python thanks to the
Code Golf challenges, here's the shortest non-recursive function I came
up with (all integers, signed):

f=lambda n:'-'[:n<0]+''.join(str(m&1)for m in iter(
lambda x=[abs(n)]:(x[0],x.__setitem__(0,x[0]>>1))[0],0))[::-1]or'0'

Any takers ? ;-)

George
 
M

MonkeeSage

So far as unobfuscated versions go, how about the simple:

def to_bin(x):
out = []
while x > 0:
out.insert(0, str(x % 2))
x = x / 2
return ''.join(out)

Regards,
Jordan
 
S

Steve Holden

MonkeeSage said:
So far as unobfuscated versions go, how about the simple:

def to_bin(x):
out = []
while x > 0:
out.insert(0, str(x % 2))
x = x / 2
return ''.join(out)

Regards,
Jordan
''

6/10: try harder :)

regards
Steve
 
P

Paul Rubin

MonkeeSage said:
def to_bin(x):
out = []
while x > 0:
out.insert(0, str(x % 2))
x = x / 2
return ''.join(out)

That returns the empty string for x=0. I'm not sure if that's a bug
or a feature.

It also returns the empty string for x < 0, probably a bug.

It will break in Python 3, where 1 / 2 == 0.5.

Here's yet another version:

def to_bin(n):
if n < 0: return '-' + to_bin(-n)
if n==0: return '0'
return ''.join(
("0000", "0001", "0010", "0011",
"0100", "0101", "0110", "0111",
"1000", "1001", "1010", "1011",
"1100", "1101", "1110", "1111",)[int(d,16)] \
for d in '%x'%n).lstrip('0')
 

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

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top