How to "reduce" a numpy array using a costum binary function

Slaunger Slaunger at gmail.com
Thu Nov 13 08:54:51 EST 2008


It is always good to ask yourself a question.
I had forgooten about the reduce function

I guess this implementation

from numpy import *

def compl_add_uint16(a, b):
    c = a + b
    c += c >> 16
    return c & 0xFFFF

def compl_one_checksum(uint16s):
    return reduce(compl_add_uint16, uint16s, 0x0000)

is somewhat better?

But is it the best way to do it with numpy?

In [2]: hex(compl_add_uint16(0xF0F0, 0x0F0F))
Out[2]: '0xffff'

In [3]: hex(compl_add_uint16(0xFFFF, 0x0001))
Out[3]: '0x1'

In [5]: hex(compl_one_checksum(array([], dtype=uint16)))
Out[5]: '0x0'

In [6]: hex(compl_one_checksum(array([0xF0F0, 0x0F0F, 0x0001],
dtype=uint16)))
Out[6]: '0x1L'



More information about the Python-list mailing list