Discussion: new operators for numerical computation

Huaiyu Zhu hzhu at localhost.localdomain
Sun Jul 30 23:14:35 EDT 2000


On Sat, 29 Jul 2000 14:07:17 +0200, Alex Martelli <alex at magenta.com> wrote:
[snip]
>> FLAG = bitwise.or(FLAG1, FLAG2, FLAG3, FLAG4, FLAG5, FLAG6, FLAG7, FLAG8)
>
>What an EXCELLENT idea.  shift left/right could also be packaged that
>way (or, almost so; 'or' is a reserved words in Python...).
>
>> quite "unpythonic" to let them occupy four unique ascii characters as
>
>Agreed, and worse if you consider << and >>.
>
[snip]
>
>The 'bitwise' module could supply easily explicit bitfield-extraction
>in place of the mask-and-shift idioms, too.
>
>Oh well -- maybe a hint for Python 3000, when backwards compatibility
>can be broken...!

Why wait that long!  Here's a prototype.  If this becomes default, it would
be easier to replace the implementation in the future - with much less to
break. 


""" 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


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
	
	print "Tests passed"




More information about the Python-list mailing list