In [1]:
%load_ext cython

Return integers to Python (no problems)


In [2]:
%%cython

def f1():
    # 2 bytes
    cdef short x = 1
    return x

def f2():
    # 4 bytes
    cdef int x = 1
    return x

def f3():
    # 4 or 8 bytes, depends on your OS
    cdef long x = 1
    return x

def f4():
    # 8 bytes
    cdef long long x = 1
    return x

In [3]:
print(type(f1()))
print(type(f2()))
print(type(f3()))
print(type(f4()))


<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>

(How to calculate max integers)


In [4]:
# Biggest unsigned short, 2 bytes => 16 bits
print(2**16 - 1)
# Biggest unsigned int, 4 bytes => 32 bits
print(2**32 - 1)
# Biggest unsigned long long, 8 bytes => 64 bits
print(2**64 - 1)


65535
4294967295
18446744073709551615

Getting integers from Python (ouch!)

Python can handle very big numbers. Be careful passing big numbers into Cython functions.


In [5]:
%%cython

cpdef can_handle_ushort(unsigned short x):
    return x

cpdef can_handle_uint(unsigned int x):
    return x

cpdef can_handle_ulong_long(unsigned long long x):
    return x

In [6]:
can_handle_ushort(2**16-1)


Out[6]:
65535

In [7]:
can_handle_ushort(2**16)


---------------------------------------------------------------------------
OverflowError                             Traceback (most recent call last)
<ipython-input-7-05a9181eee46> in <module>()
----> 1 can_handle_ushort(2**16)

_cython_magic_9914932b4fcdbf5943b5545fab2c5c45.pyx in _cython_magic_9914932b4fcdbf5943b5545fab2c5c45.can_handle_ushort (/Users/siuser/.ipython/cython/_cython_magic_9914932b4fcdbf5943b5545fab2c5c45.c:828)()

OverflowError: value too large to convert to unsigned short

In [8]:
can_handle_uint(2**32-1)


Out[8]:
4294967295

In [9]:
can_handle_uint(2**32)


---------------------------------------------------------------------------
OverflowError                             Traceback (most recent call last)
<ipython-input-9-129e73c49f5f> in <module>()
----> 1 can_handle_uint(2**32)

_cython_magic_9914932b4fcdbf5943b5545fab2c5c45.pyx in _cython_magic_9914932b4fcdbf5943b5545fab2c5c45.can_handle_uint (/Users/siuser/.ipython/cython/_cython_magic_9914932b4fcdbf5943b5545fab2c5c45.c:922)()

OverflowError: value too large to convert to unsigned int

In [10]:
can_handle_ulong_long(2**64-1)


Out[10]:
18446744073709551615

In [11]:
can_handle_ulong_long(2**64)


---------------------------------------------------------------------------
OverflowError                             Traceback (most recent call last)
<ipython-input-11-5036d43b3424> in <module>()
----> 1 can_handle_ulong_long(2**64)

_cython_magic_9914932b4fcdbf5943b5545fab2c5c45.pyx in _cython_magic_9914932b4fcdbf5943b5545fab2c5c45.can_handle_ulong_long (/Users/siuser/.ipython/cython/_cython_magic_9914932b4fcdbf5943b5545fab2c5c45.c:1012)()

OverflowError: Python int too large to convert to C unsigned long

In [ ]: