new bitwise module [was Re: Discussion: new operators ...]
Alex Martelli
alex at magenta.com
Tue Aug 1 08:11:59 EDT 2000
"Huaiyu Zhu" <hzhu at localhost.localdomain> wrote in message
news:slrn8obed7.17f.hzhu at rocket.knowledgetrack.com...
[snip]
> Excellent. So let's put them in. I don't know what they do as I don't
use
> bitwise operations, but I suppose they are simple to write on top of
current
> bitwise operators. Would you do it?
Why, sure. Also reposting your original stuff for completeness:
""" bitwise.py - replaces builtin bitwise operations with named functions
"""
def bitleft(x, bits):
return x << bits
def bitright(x, bits):
return x >> bits
def bitshift(x, bits):
"shift left (positive bits) or right (negative bits)."
if bits >= 0:
return x << bits
else:
return x >> -bits
def bitnot(x):
return ~x
def bitxor(x1, x2):
return x1 ^ x2
def bitor(*args):
y = 0
for x in args:
y = y | x
return y
def bitand(*args):
y = ~0
for x in args:
y = y & x
return y
def bitset(x, bitoff, value=1):
"return an int with a specified bit set"
if value:
return x|(1<<bitoff)
else:
return x&~(1<<bitoff)
def bitclear(x, bitoff):
"return an int with a specified bit zeroed"
return x&~(1<<bitoff)
def bitget(x, bitoff):
"get a specified bit from an int as 0 or 1"
return (x>>bitoff)&1
def bitflip(x, bitoff):
"return an int with a specified bit inverted"
return x^(1<<bitoff)
def bitfieldget(x, bitoff, nbits):
"get a specified bitfield from an int"
mask=(1<<nbits)-1
return (x>>bitoff) & mask
def bitfieldset(x, bitoff, nbits, value):
"return an int with a specified bitfield set"
mask=(1<<nbits)-1
return (x&~(mask<<bitoff))|((value&mask)<<bitoff)
if __name__ == "__main__":
assert bitleft(16,2) == 64
assert bitright(16,3) == 2
assert bitshift(16,2) == 64
assert bitshift(16,-3) == 2
assert bitnot(7) == -8
assert bitxor(6,7) == 1
assert bitand(6,7) == 6
assert bitor(6,7) == 7
assert bitand(4,5,6) == 4
assert bitor(4,5,6) == 7
assert bitset(16,2) == 20
assert bitset(7,1,0) == 5
assert bitget(5,1) == 0
assert bitflip(5,1) == 7
assert bitfieldget(0xf0,4,2) == 3
assert bitfieldset(0xf0,0,2,2) == 0xf2
print "Tests passed"
> >Maybe it could get into the Standard Distribution, and it would be
trivial
> >to supply a C implementation of course (cBitfield perhaps?). No way to
[snip]
> That's the idea. So let's have it. That would make adding new math
> operators a little easier to swallow as well. :-)
OK, so, how does one proceed now? We have a new simple and general
purpose module that we believe might be beneficial to include in the
standard distribution -- what do we send were to submit it? Anybody knows?
Alex
More information about the Python-list
mailing list