[Tutor] Multiplication without overflow
Abel Daniel
abli@freemail.hu
Fri Jul 4 05:30:03 2003
Jimmy verma wrote:
> I am having some problem in understanding this small one line function in
> python.
>
> def u16mult(a,b):
> return ((a*(b&0x0fff)&0xffff)+(((a*(b>>12))&0x000f)<<12))&0xffff
>
> we need a multiplication function that will handle 16-bit unsigned values
> without the overflow that 32-bit signed values can suffer from.
What overflow?
Python 2.2.2 (#1, Mar 21 2003, 23:01:54)
[GCC 3.2.3 20030316 (Debian prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a=2**32
>>> a
4294967296L
>>> a*a
18446744073709551616L
>>>
Abel Daniel