473,657 Members | 2,479 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Efficient Bit addressing in Python.


Is there a canonical way to address the bits in a structure
like an array or string or struct?

Or alternatively, is there a good way to combine eight
ints that represent bits into one of the bytes in some
array or string or whatever?

It seems to me that there is a dilemma here :

if you can write:

bit3 = 1

Then you have to jump through hoops to get
bit0 through bit7 into some byte that you can send
to an i/o routine.

On the other hand, if you keep the bits "in" the
byte, then you can write:

byte[3] = '\x7e'

but you have to jump through hoops to get at
the individual bits.

Is there a "best" way?

It would be nice to be able to write:

if io.byte2.bit3:
do_something()

if io.byte2 == alarm_value:
do_something_el se()

where:

io.byte2 & 8 "is" io.byte2.bit3

Is this possible?

- Hendrik

Oct 9 '08 #1
5 1439
On Oct 9, 6:30 pm, "Hendrik van Rooyen" <m...@microcorp .co.zawrote:
Is there a canonical way to address the bits in a structure
like an array or string or struct?
I don't know of a canonical way (bit hacking is not really common in
Python) but pehaps BitPacket [1] comes close to what you're after.

George

[1] http://hacks-galore.org/aleix/BitPacket/
Oct 9 '08 #2
On Oct 9, 5:30*pm, "Hendrik van Rooyen" <m...@microcorp .co.zawrote:
Is there a canonical way to address the bits in a structure
like an array or string or struct?

Or alternatively, is there a good way to combine eight
ints that represent bits into one of the bytes in some
array or string or whatever?

It seems to me that there is a dilemma here :

if you can write:

bit3 = 1

Then you have to jump through hoops to get
bit0 through bit7 into some byte that you can send
to an i/o routine.

On the other hand, if you keep the bits "in" the
byte, then you can write:

byte[3] = '\x7e'

but you have to jump through hoops to get at
the individual bits.

Is there a "best" way?

It would be nice to be able to write:

if io.byte2.bit3:
* *do_something()

if io.byte2 == alarm_value:
* do_something_el se()

where:

*io.byte2 & 8 * "is" *io.byte2.bit3

Is this possible?

- Hendrik
I use the gmpy module for all my bit related work and
have been very satisfied with the results.

Examples of functions pertinent to bit operations:

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.

Oct 9 '08 #3
Hendrik van Rooyen <ma**@microcorp .co.zawrote:
>Is there a canonical way to address the bits in a structure
like an array or string or struct?

Or alternatively, is there a good way to combine eight
ints that represent bits into one of the bytes in some
array or string or whatever?
This is the code I use to convert large bit arrays to byte strings and
back:

import string
import binascii
import array

_tr_16 = string.maketran s("0123456789ab cdef",
"\x00\x01\x02\x 03"
"\x10\x11\x12\x 13"
"\x20\x21\x22\x 23"
"\x30\x31\x32\x 33")
_tr_4 = string.maketran s("0123",
"\x00\x01"
"\x10\x11")
_tr_2 = string.maketran s("01", "\x00\x01")

def string_to_bit_a rray(s):
"""Convert a string to an array containing a sequence of bits."""
s = binascii.hexlif y(s).translate( _tr_16)
s = binascii.hexlif y(s).translate( _tr_4)
s = binascii.hexlif y(s).translate( _tr_2)
a = array.array('B' , s)
return a

_tr_rev_2 = string.maketran s("\x00\x01", "01")
_tr_rev_4 = string.maketran s("\x00\x01"
"\x10\x11",
"0123")
_tr_rev_16 = string.maketran s("\x00\x01\x02 \x03"
"\x10\x11\x12\x 13"
"\x20\x21\x22\x 23"
"\x30\x31\x32\x 33",
"0123456789abcd ef")
def bit_array_to_st ring(a):
"""Convert an array containing a sequence of bits to a string."""
remainder = len(a) % 8
if remainder != 0:
a.fromlist([0] * (8 - remainder))
s = a.tostring()
s = binascii.unhexl ify(s.translate (_tr_rev_2))
s = binascii.unhexl ify(s.translate (_tr_rev_4))
return binascii.unhexl ify(s.translate (_tr_rev_16))

I don't think you can do anything faster with standard modules, although
it might not be effecient if you're only working with a single byte.

Ross Ridge

--
l/ // Ross Ridge -- The Great HTMU
[oo][oo] rr****@csclub.u waterloo.ca
-()-/()/ http://www.csclub.uwaterloo.ca/~rridge/
db //
Oct 10 '08 #4
On Oct 9, 5:30*pm, "Hendrik van Rooyen" <m...@microcorp .co.zawrote:
Is there a canonical way to address the bits in a structure
like an array or string or struct?

Or alternatively, is there a good way to combine eight
ints that represent bits into one of the bytes in some
array or string or whatever?

It seems to me that there is a dilemma here :

if you can write:

bit3 = 1

Then you have to jump through hoops to get
bit0 through bit7 into some byte that you can send
to an i/o routine.

On the other hand, if you keep the bits "in" the
byte, then you can write:

byte[3] = '\x7e'

but you have to jump through hoops to get at
the individual bits.

Is there a "best" way?

It would be nice to be able to write:

if io.byte2.bit3:
* *do_something()

if io.byte2 == alarm_value:
* do_something_el se()

where:

*io.byte2 & 8 * "is" *io.byte2.bit3

Is this possible?

- Hendrik
This is tolerable. If you've got a better 'clear' operation than
'xor', you're welcome to it.

class BitSet:
def __init__( self, value ):
self.value= value
def __setitem__( self, index, value ):
if value:
self.value= self.value| (1<< index)
elif self[ index ]:
self.value= self.value^ (1<< index)
def __getitem__( self, index ):
return self.value& (1<< index )
def __repr__( self ):
return repr( self.value )

if __name__== '__main__':
b= BitSet( 15 )
print b
b[0]= 0
print b
b[0]= 1
print b
b[4]= 1
print b
b[4]= 0
print b

/Output:
15
14
15
31
15
Oct 11 '08 #5
On Oct 10, 10:37*pm, "Aaron \"Castironpi \" Brady"
<castiro...@gma il.comwrote:
On Oct 9, 5:30*pm, "Hendrik van Rooyen" <m...@microcorp .co.zawrote:
Is there a canonical way to address the bits in a structure
like an array or string or struct?
Or alternatively, is there a good way to combine eight
ints that represent bits into one of the bytes in some
array or string or whatever?
snip
>
class BitSet:
* * def __init__( self, value ):
* * * * self.value= value
* * def __setitem__( self, index, value ):
* * * * if value:
* * * * * * self.value= self.value| (1<< index)
* * * * elif self[ index ]:
* * * * * * self.value= self.value^ (1<< index)
* * def __getitem__( self, index ):
* * * * return self.value& (1<< index )
snip

This could read:

def __getitem__( self, index ):
return 1 if self.value& (1<< index ) else 0

Or you could shift self.value, and mask with unity.
Oct 11 '08 #6

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

Similar topics

4
2391
by: Jakub Fast | last post by:
Hi, Does anybody know how far you can get nowadays with trying to use Python as the script language for XUL instead of JS? Is it possible (even theoretically) to write full-fledged applications on the Mozilla platform with python only? In a parallel vein, anybody know what the architecture of Komodo is? Thanks for any pointers, information, etc
0
2047
by: Stefan Lischke | last post by:
Hi, I'm really desperate using code generation(wsdl.exe) from wsdl files for latest WS-Eventing(including WS-Addressing) Specs. I'm writing my diploma about "publish subscribe systems based on Web Services" I took the WS-Eventing WSDL file and added <binding>'s and <service>'s... Then i took the apache axis wsdl2java tool and i got nice
12
4367
by: s99999999s2003 | last post by:
hi I have a file which is very large eg over 200Mb , and i am going to use python to code a "tail" command to get the last few lines of the file. What is a good algorithm for this type of task in python for very big files? Initially, i thought of reading everything into an array from the file and just get the last few elements (lines) but since it's a very big file, don't think is efficient. thanks
3
2049
by: Doru-Catalin Togea | last post by:
Hi! I am writing some tests and I need to place calls through the modem. Is there an API for addressing the COM ports on my machine, so that I can issue AT-commands to the modem? If this can not be done from Python, I am sure it can be done from C/C++/Java. Any tutorials/examples that you know of? Maybe calling C from Python?
10
3760
by: noro | last post by:
Is there a more efficient method to find a string in a text file then: f=file('somefile') for line in f: if 'string' in line: print 'FOUND' ? BTW:
0
1325
by: gerritmitchell | last post by:
Hi, I have a situation where I need to send a SOAP message from a receiver through multiple intermediaries and then to an ultimate receiver. The intial sender will tell the intermediary where to send the message to next within the service chain. SOAP targeted headers and SOAP roles seem to suppor this quite well. My question is can this be used in conjunction with WS-Addressing? Meaning can I send a WS-Addressing compliant message...
1
4094
by: =?Utf-8?B?dWx0cmFuZXQ=?= | last post by:
We have a client that uses .Net that needs to work against our Java (xfire) based WS. My question is: how can a .Net (C#) WS client be configured to not send WS-Addressing headers? The client in particular mentions having tried WSE 2.0, and WSE 3.0, and says there is no way to turn off WS-Addressing in a WS client, using those frameworks. I find that very hard to believe. There appears to be a problem w/ WS-Addressing headers in the...
5
3160
by: Ross | last post by:
Forgive my newbieness - I want to refer to some variables and indirectly alter them. Not sure if this is as easy in Python as it is in C. Say I have three vars: oats, corn, barley I add them to a list: myList Then I want to past that list around and alter one of those values. That is I want to increment the value of corn:
0
160
by: Lie Ryan | last post by:
On Fri, 10 Oct 2008 00:30:18 +0200, Hendrik van Rooyen wrote: You'll find that in most cases, using integer or Boolean is enough. There are some edge cases, which requires bit addressing for speed or memory optimizations, in python, the usual response to that kind of optimization requirement is to move that part of the code to C. If, for the more usual case, you require the bit addressing because the data structure is more convenient...
0
8421
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8844
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8742
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8518
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8621
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7354
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4173
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2743
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1734
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.