473,465 Members | 1,903 Online
Bytes | Software Development & Data Engineering Community
Create 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_else()

where:

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

Is this possible?

- Hendrik

Oct 9 '08 #1
5 1427
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_else()

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.maketrans("0123456789abcdef",
"\x00\x01\x02\x03"
"\x10\x11\x12\x13"
"\x20\x21\x22\x23"
"\x30\x31\x32\x33")
_tr_4 = string.maketrans("0123",
"\x00\x01"
"\x10\x11")
_tr_2 = string.maketrans("01", "\x00\x01")

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

_tr_rev_2 = string.maketrans("\x00\x01", "01")
_tr_rev_4 = string.maketrans("\x00\x01"
"\x10\x11",
"0123")
_tr_rev_16 = string.maketrans("\x00\x01\x02\x03"
"\x10\x11\x12\x13"
"\x20\x21\x22\x23"
"\x30\x31\x32\x33",
"0123456789abcdef")
def bit_array_to_string(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.unhexlify(s.translate(_tr_rev_2))
s = binascii.unhexlify(s.translate(_tr_rev_4))
return binascii.unhexlify(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.uwaterloo.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_else()

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...@gmail.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
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...
0
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...
12
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...
3
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...
10
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
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...
1
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...
5
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...
0
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...
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,...
1
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...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
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 ...

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.