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

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

Hi,

String formatting can be used to converting an integer to its octal or
hexadecimal form:
>>a = 199
"%o" % a
'307'
>>"%x" % a
'c7'

But, can string formatting be used to convert an integer to its binary
form ?
Thanks in advance.

xiaojf
Sep 28 '06 #1
27 2786
fd********@gmail.com schreef:
Hi,

String formatting can be used to converting an integer to its octal or
hexadecimal form:
>>>a = 199
"%o" % a
'307'
>>>"%x" % a
'c7'

But, can string formatting be used to convert an integer to its binary
form ?
Thanks in advance.

xiaojf
I don't actually know how to do it with string formatting but you can
create a simple function to do it.
Here's an example:
http://aspn.activestate.com/ASPN/Coo.../Recipe/219300

Regards,
Benedict
Sep 28 '06 #2
Thus spoke fd********@gmail.com (on 2006-09-28 09:10):
String formatting can be used to converting an integer to its octal or
hexadecimal form:
>>a = 199
>>"%o" % a
'307'
>>"%x" % a
'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
Sep 28 '06 #3
At Thursday 28/9/2006 05:22, Mirco Wahab wrote:
String formatting can be used to converting an integer to its octal or
hexadecimal form:
>>a = 199
>>"%o" % a
'307'
>>"%x" % a
'c7'

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

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

Sep 28 '06 #4
Thus spoke Gabriel Genellina (on 2006-09-28 11:05):
At Thursday 28/9/2006 05:22, Mirco Wahab wrote:
But, can string formatting be used to convert an integer to its binary
form ?

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".
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
Sep 28 '06 #5
Mirco Wahab:
But where is the %b in Python?
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/Coo.../Recipe/440528

Bye,
bearophile

Sep 28 '06 #6
be************@lycos.com wrote:
Mirco Wahab:
>But where is the %b in Python?

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/Coo.../Recipe/440528

Bye,
bearophile

Good idea, but shorter with ->
http://cheeseshop.python.org/pypi/SE/2.2%20beta
>>import SE
Int_To_Binary = SE.SE (SE.SE ('0=0000 1=0001 2=0010 3=0011 4=0100
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')
>>Int_To_Binary ('%x' % 1234567890')
'01001001100101100000001011010010'
>>Int_To_Binary.save ('se_definition_files/int_to_binary.se')
>>SE.SE ('se_definition_files/int_to_binary.se') ('%X' % 987654321)
'00111010110111100110100010110001'
Frederic

Sep 28 '06 #7
Thus spoke Frederic Rentsch (on 2006-09-28 20:43):
be************@lycos.com wrote:
>Mirco Wahab:
>>But where is the %b in Python?

Python doesn't have that. ...
http://aspn.activestate.com/ASPN/Coo.../Recipe/440528

Good idea, but shorter with ->
http://cheeseshop.python.org/pypi/SE/2.2%20beta
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
Sep 28 '06 #8
In <ef**********@mlucom4.urz.uni-halle.de>, Mirco Wahab wrote:
Thus spoke Frederic Rentsch (on 2006-09-28 20:43):
>be************@lycos.com wrote:
>>Mirco Wahab:

But where is the %b in Python?

Python doesn't have that. ...
http://aspn.activestate.com/ASPN/Coo.../Recipe/440528

Good idea, but shorter with ->
http://cheeseshop.python.org/pypi/SE/2.2%20beta
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(...)
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
Sep 28 '06 #9
Mirco Wahab wrote:
- why doesn't have Python such a simple and useful thing as to_binstr(...)
useful? really? for what?

</F>

Sep 28 '06 #10
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
Sep 28 '06 #11
Thus spoke Fredrik Lundh (on 2006-09-28 23:35):
Mirco Wahab wrote:
>- why doesn't have Python such a simple and useful thing as to_binstr(...)

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
Sep 28 '06 #12
Frederic Rentsch:
Good idea, but shorter with ->
>>SE.SE ('se_definition_files/int_to_binary.se') ('%X' % 987654321)
'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

Sep 28 '06 #13
In message <11*********************@m7g2000cwm.googlegroups.c om>, be************@lycos.com wrote:
Mirco Wahab:
>But where is the %b in Python?

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/Coo.../Recipe/440528
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)])

Sep 29 '06 #14
In message <ef**********@lust.ihug.co.nz>, I wrote:
"".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. :)
Sep 29 '06 #15
At Thursday 28/9/2006 22:07, Lawrence D'Oliveiro wrote:
>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

Sep 29 '06 #16
Gabriel Genellina wrote:
At Thursday 28/9/2006 22:07, Lawrence D'Oliveiro wrote:
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

Sep 29 '06 #17
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

Sep 29 '06 #18
MonkeeSage wrote:
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
>>to_bin(0)
''

6/10: try harder :)

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

Sep 29 '06 #19
"MonkeeSage" <Mo********@gmail.comwrites:
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')
Sep 29 '06 #20
Steve Holden wrote:
MonkeeSage wrote:
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
>>to_bin(0)
''

6/10: try harder :)
Ok, how about a fast *and* readable version? Works for non-negatives,
but negatives are trivial to add if necessary:

from array import array

def fast2bin(n):
s = array('c')
while n>0:
s.append('01'[n&1])
n >>= 1
s.reverse()
return s.tostring() or '0'

try: import psyco
except ImportError: pass
else: psyco.bind(fast2bin)
George

Sep 29 '06 #21
Steve Holden wrote:
>>to_bin(0)
''
Doh! Oh, yeah...that! ;)

OK...

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

Regards,
Jordan

Sep 29 '06 #22
MonkeeSage wrote:
Steve Holden wrote:
> >>to_bin(0)
''


Doh! Oh, yeah...that! ;)

OK...

def to_bin(x):
out=[]
while x 0:
out.insert(0, str(x % 2))
x /= 2
else:
out.append(str(x))
return ''.join(out)
It's an often-missed and almost invariably untested corner case that
one's first attempt to solve the problem usually rids one of. I have
written binary format code about thirteen times in a lifetime of
programming so it was easy for me to spot. You'll never make *that*
mistake again ;-)

Unfortunately forty years of programming experience has taught me that
there's an essentially infinite supply of mistakes to make ... your
mistakes just get smarter most of the time.

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

Sep 29 '06 #23
be************@lycos.com wrote:
Frederic Rentsch:
>Good idea, but shorter with ->
> >>SE.SE ('se_definition_files/int_to_binary.se') ('%X' % 987654321)
'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

If you say speed, I presume you mean speed of execution. No I have not
tested that. I know it can't be fast on a test bench. After all, SE is
written in Python. I did a first version fifteen years ago in C, am
still using it today on occasion and it runs much, much faster than this
Python SE. This SE here could be done in C if it passes the test of
acceptance.
Professionals need to measure execution speed as a part of
documenting their products. I am not a professional and so I am free to
define my own scale of grades: A (fast enough) and F (not fast enough).
I have yet to encounter a situation where SE gets an F. But that says
less about SE than about my better knowledge which prevents me from
using SE to, say, change colors in a 50 Mb bitmap. Obviously, "fast
enough" and "not fast enough" pertains not to code per se, but to code
in a specific situation. So, as the saying goes: the proof of the
pudding ...
Another kind of speed is production speed. I do believe that SE
rather excels on that side. I also believe that the two kinds of speed
are economically related by the return-on-investment principle.
The third kind of speed is learning speed. SE is so simple that it
has no technical learning curve to speak of. It's versatility comes from
a wealth of application techniques that invite exploration, invention
even. Take leading zeroes:

Leading zeroes can be stripped in a second pass if they are made
recognizable in the first pass by some leading mark that is not a zero
or a one. ([^01]; I use "@" in the following example). To purists this
may seem hackish. So it is! And what's wrong with that if it leads to
simpler solutions?
>>Hex_To_Binary = SE.SE ('0=0000 1=0001 2=0010 3=0011 4=0100 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 | ~[^01]0*~=')
>>Hex_To_Binary.set (keep_chain = 1)
Hex_To_Binary ('@%x' % 1234567890)
'1001001100101100000001011010010'
>>Hex_To_Binary.show ()
.... snip ...

Data Chain
----------------------------------------------------------------------------------
@499602d2
0
--------------------------------------------------------------------------------
@01001001100101100000001011010010
1
--------------------------------------------------------------------------------
1001001100101100000001011010010
----------------------------------------------------------------------------------
Frederic

(The previously posted example "Int_To_Binary = SE.SE (SE.SE ( ..." was
a typo, or course. One (SE.SE does it. Sorry about that.)

Sep 29 '06 #24
On 9/29/06, Steve Holden <st***@holdenweb.comwrote:
Unfortunately forty years of programming experience has taught me that
there's an essentially infinite supply of mistakes to make ... your
mistakes just get smarter most of the time.
+1 QOTW.

--
Cheers,
Simon B,
si***@brunningonline.net
Sep 29 '06 #25
On 2006-09-29, Steve Holden <st***@holdenweb.comwrote:
MonkeeSage wrote:
>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,
It was surprising that
>>i = int("111010101", 2)
is a one-way operation.
>>s = str(i, 2)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: str() takes at most 1 argument (2 given)

--
Neil Cerutti
Sep 29 '06 #26
Neil Cerutti wrote:
On 2006-09-29, Steve Holden <st***@holdenweb.comwrote:
>MonkeeSage wrote:
>>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,

It was surprising that
>>>i = int("111010101", 2)

is a one-way operation.
>>>s = str(i, 2)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: str() takes at most 1 argument (2 given)
str() is not only for converting integers, but all other types too.
An explicit argument for this special case is not Pythonic IMO.

Georg
Sep 29 '06 #27
On 2006-09-29, Georg Brandl <g.*************@gmx.netwrote:
Neil Cerutti wrote:
>On 2006-09-29, Steve Holden <st***@holdenweb.comwrote:
>>MonkeeSage wrote:
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,

It was surprising that
>>>>i = int("111010101", 2)

is a one-way operation.
>>>>s = str(i, 2)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: str() takes at most 1 argument (2 given)

str() is not only for converting integers, but all other types
too. An explicit argument for this special case is not Pythonic
IMO.
I suppose two wrongs wouldn't make a right. ;)

--
Neil Cerutti
Sep 29 '06 #28

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

Similar topics

3
by: Convert TextBox.Text to Int32 Problem | last post by:
Need a little help here. I saw some related posts, so here goes... I have some textboxes which are designed for the user to enter a integer value. In "old school C" we just used the atoi function...
4
by: Dennis Myrén | last post by:
Hi. Is there a way to utilize the great primitive data type formatting routines available in .NET without working with strings? I want a byte directly rather than a string. I think it is...
9
by: rsine | last post by:
I have developed a program that sends a command through the serial port to our business system and then reads from the buffer looking for a number. Everything worked great on my WinXP system, but...
43
by: Steven T. Hatton | last post by:
http://public.research.att.com/~bs/bs_faq2.html#int-to-string Is there no C library function that will take an int and convert it to its ascii representation? The example Bjarne shows in his faq...
11
by: RipperT | last post by:
Don't know if this group covers web apps, but here goes. In VS 2005, I am trying to get variables to hold thier values during postback from the server. I convert a text box's user-keyed value to an...
14
by: Scott M. | last post by:
Ok, this is driving me nuts... I am using VS.NET 2003 and trying to take an item out of a row in a loosely-typed dataset and place it in a label as a currency. As it is now, I am getting my...
16
by: Hugh Janus | last post by:
Hi all, I am using the below functions in order to convert strings to bytes and vice versa. I totally ans shamefully stole these functions from this group btw! Anyway, they work great but as...
2
by: Brian Parker | last post by:
I am beginning to work with VB2005.NET and I'm getting some problems with string formatting converting an application from VB6. VB6 code:- sTradeDate = Format(pArray(4,i Record), "mmddyy") ...
28
by: pradeep | last post by:
Hello friends: I know some people here don't like to answer C++ questions, but I believe this is really about the underlying C code. Anyway I have posted as well to the other group someone...
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
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...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.