473,407 Members | 2,315 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,407 software developers and data experts.

binary representation of an integer

Hello,

I'm interested in converting integers to a binary representation,
string. I.e. a desired function would produce:

dec2bin(13) ="1101"

The other way is easily done in Python with the int() function.

Perl has a very efficient way to do dec2bin, because its pack/unpack
have a B format for binary representations, so it's done with:

sub dec2bin {
my $str = unpack("B32", pack("N", shift));
$str =~ s/^0+(?=\d)//; # otherwise you'll get leading zeros
return $str;
}

Python's pack/unpack don't have the binary format for some reason, so
custom solutions have to be developed. One suggested in the ASPN
cookbook is:
http://aspn.activestate.com/ASPN/Coo.../Recipe/111286
However, it is very general and thus inefficient.

What would be the quickest way to do this ? I think that for dec2bin
conversion, using hex() and then looping with a hex->bin lookup table
would be probably much faster than the general baseconvert from the
recipe.

What do you think?
Jun 27 '08 #1
7 2897
Le Tuesday 24 June 2008 10:03:58 eliben, vous avez écrit*:
Hello,

I'm interested in converting integers to a binary representation,
string. I.e. a desired function would produce:

dec2bin(13) ="1101"

The other way is easily done in Python with the int() function.

Perl has a very efficient way to do dec2bin, because its pack/unpack
have a B format for binary representations, so it's done with:

sub dec2bin {
my $str = unpack("B32", pack("N", shift));
$str =~ s/^0+(?=\d)//; # otherwise you'll get leading zeros
return $str;
}

Python's pack/unpack don't have the binary format for some reason,
Yes, but I think the %b format specifier has been added to p3k but will notin
python 2.x.
so
custom solutions have to be developed. One suggested in the ASPN
cookbook is:
http://aspn.activestate.com/ASPN/Coo.../Recipe/111286
However, it is very general and thus inefficient.

What would be the quickest way to do this ? I think that for dec2bin
conversion, using hex() and then looping with a hex->bin lookup table
would be probably much faster than the general baseconvert from the
recipe.

What do you think?

Something like that, less typing with octal conversion :)
>>>[8]: oct2bin =
{'0':'000', '1':'001', '2':'010', '3':'011', '4':'100', '5':'101', '6':'110', '7':'111'}
>>>[9]: ''.join(oct2bin[e] for e in "%o"%35).lstrip('0')
...[9]: '100011'

--
_____________

Maric Michaud
_____________

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 4 26 88 00 97
Mobile: +33 6 32 77 00 21
Jun 27 '08 #2
On Jun 24, 9:03*am, eliben <eli...@gmail.comwrote:
What would be the quickest way to do this ? I think that for dec2bin
conversion, using hex() and then looping with a hex->bin lookup table
would be probably much faster than the general baseconvert from the
recipe.
I suspect you're right, but it would be easy to find out: just
code up the hex->bin method and use the timeit module to do some
timings. Don't forget to strip the trailing 'L' from hex(n) if n
is a long.

If you're prepared to wait for Python 2.6, or work with the beta
version, then the conversion is already there:

Macintosh-3:trunk dickinsm$ ./python.exe
Python 2.6b1+ (trunk:64489, Jun 23 2008, 21:10:40)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>bin(13)
'0b1101'

Interestingly, unlike hex and oct, bin doesn't add a trailing
'L' for longs:
>>bin(13L)
'0b1101'

I wonder whether this is a bug...

Mark
Jun 27 '08 #3
eliben <el****@gmail.comwrote:
I'm interested in converting integers to a binary representation,
string. I.e. a desired function would produce:

dec2bin(13) ="1101"

The other way is easily done in Python with the int() function.

Perl has a very efficient way to do dec2bin, because its pack/unpack
have a B format for binary representations, so it's done with:

sub dec2bin {
my $str = unpack("B32", pack("N", shift));
$str =~ s/^0+(?=\d)//; # otherwise you'll get leading zeros
return $str;
}

Python's pack/unpack don't have the binary format for some reason, so
custom solutions have to be developed. One suggested in the ASPN
cookbook is:
http://aspn.activestate.com/ASPN/Coo.../Recipe/111286
However, it is very general and thus inefficient.

What would be the quickest way to do this ? I think that for dec2bin
conversion, using hex() and then looping with a hex->bin lookup table
would be probably much faster than the general baseconvert from the
recipe.

What do you think?
Something like this...
>>hex_to_binary = {
.... "0" : "0000",
.... "1" : "0001",
.... "2" : "0010",
.... "3" : "0011",
.... "4" : "0100",
.... "5" : "0101",
.... "6" : "0110",
.... "7" : "0111",
.... "8" : "1000",
.... "9" : "1001",
.... "a" : "1010",
.... "b" : "1011",
.... "c" : "1100",
.... "d" : "1101",
.... "e" : "1110",
.... "f" : "1111",
.... }
>>def to_binary(inp):
.... out = []
.... for hex_digit in ("%x" % inp):
.... out.append(hex_to_binary[hex_digit])
.... out = "".join(out).lstrip("0")
.... if out == "":
.... out = "0"
.... return out
....
>>to_binary(0)
'0'
>>to_binary(10)
'1010'
>>to_binary(100)
'1100100'
>>to_binary(1000)
'1111101000'
>>to_binary(10000000000000000000)
'1000101011000111001000110000010010001001111010000 000000000000000'

But don't try this ;-)
>>to_binary(-1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in to_binary
KeyError: '-'

--
Nick Craig-Wood <ni**@craig-wood.com-- http://www.craig-wood.com/nick
Jun 27 '08 #4
On Jun 24, 10:38 am, Mark Dickinson <dicki...@gmail.comwrote:
On Jun 24, 9:03 am, eliben <eli...@gmail.comwrote:
What would be the quickest way to do this ? I think that for dec2bin
conversion, using hex() and then looping with a hex->bin lookup table
would be probably much faster than the general baseconvert from the
recipe.

I suspect you're right, but it would be easy to find out: just
code up the hex->bin method and use the timeit module to do some
timings. Don't forget to strip the trailing 'L' from hex(n) if n
is a long.

If you're prepared to wait for Python 2.6, or work with the beta
version, then the conversion is already there:

Macintosh-3:trunk dickinsm$ ./python.exe
Python 2.6b1+ (trunk:64489, Jun 23 2008, 21:10:40)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.>>bin(13)

'0b1101'

Interestingly, unlike hex and oct, bin doesn't add a trailing
'L' for longs:
>bin(13L)

'0b1101'

I wonder whether this is a bug...

Mark
Strange in 2.6, but I know at least in 3.0 that all integers are C
Long's now, so the L is no longer required.
Jun 27 '08 #5
And:

# return as a string
def itob_string(integer, count = 8):
return "".join(str((integer >i) & 1) for i in range(count - 1,
-1, -1))

# return as an iterator (i.e [0, 0, 0, 0, 1, 0, 1, 0])
def itob_list(integer, count = 8):
return [(integer >i) & 1 for i in range(count - 1, -1, -1)]

# return as a generator
def itob_generator(integer, count = 8):
return ((integer >i) & 1 for i in range(count - 1, -1, -1))
Jun 27 '08 #6
eliben:
Python's pack/unpack don't have the binary format for some reason, so
custom solutions have to be developed. One suggested in the ASPN
cookbook is:http://aspn.activestate.com/ASPN/Coo.../Recipe/111286
However, it is very general and thus inefficient.
Try mine, it may be fast enough for your purposes:
http://aspn.activestate.com/ASPN/Coo.../Recipe/440528

Bye,
bearophile
Jun 27 '08 #7


co*********@gmail.com wrote:
On Jun 24, 10:38 am, Mark Dickinson <dicki...@gmail.comwrote:
>Interestingly, unlike hex and oct, bin doesn't add a trailing
'L' for longs:
>>>>bin(13L)
'0b1101'

I wonder whether this is a bug...
Strange in 2.6, but I know at least in 3.0 that all integers are C
Long's now, so the L is no longer required.
In current 2.x, the trailing L is no longer required for long integer
input; the lexer decides whether to make an int or long. Similarly,
ints are automatically converted to longs as needed instead of raising
overflow errors (as once happended). The trailing L on output would
have been removed already except for backward compatibility. But there
was no back-compatibility requirement for 0bxxxx strings.

In 3.0, all integers are class 'int'. The internal representation as
fixed or extended precision is entirely an internal implementation matter.

Jun 27 '08 #8

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

Similar topics

0
by: Mark Dufour | last post by:
Hi all, I need to convert an integer into some binary representation. I found the following code in the online cookbook (adapted to return a list): binary = lambda n: n>0 and +binary(n>>1) or ...
20
by: Christian Stigen Larsen | last post by:
A signed int reserves one bit to signify whether a number is positive or negative. In light of this, a colleague asked me whether there existed an int in C++ that was -0, a zero with the negative...
10
by: J. Campbell | last post by:
OK...I'm in the process of learning C++. In my old (non-portable) programming days, I made use of binary files a lot...not worrying about endian issues. I'm starting to understand why C++ makes...
6
by: Andrew | last post by:
Hi I have a question is there a function in C++ to convert an integer into a Binary number Thanks in Advance Cheers
3
by: Tanuki | last post by:
Hi All: I encounter a programming problem recently. I need to read a binary file. I need to translate the binary data into useful information. I have the format at hand, like 1st byte = ID,...
8
by: Yeow | last post by:
hello, i was trying to use the fread function on SunOS and ran into some trouble. i made a simple test as follows: i'm trying to read in a binary file (generated from a fortran code) that...
10
by: 63q2o4i02 | last post by:
Hi, I'm using python to run some lab equipment using PyVisa. When I read a list of values from the equipment, one of the fields is 32 bits of flags, but the value is returned as a floating...
3
by: shyha | last post by:
Hello! Does anybody know what is binary representation of integer datatype fields written to archlogs on z/OS (OS/390) machines? Is it "Two's complement", "One's complement", Sign-modulo or...
7
by: elliotng.ee | last post by:
I have a text file that contains a header 32-bit binary. For example, the text file could be: %%This is the input text %%test.txt Date: Tue Dec 26 14:03:35 2006...
26
by: Carramba | last post by:
Hi! How can I output value of char or int in binary form with printf(); ? thanx in advance
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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
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
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
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
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
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,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new...

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.