简体   繁体   中英

Convert int64 to uint64

I want to convert an int64 numpy array to a uint64 numpy array, adding 2**63 to the values in the process so that they are still within the valid range allowed by the arrays. So for example if I start from

a = np.array([-2**63,2**63-1], dtype=np.int64)

I want to end up with

np.array([0.,2**64], dtype=np.uint64)

Sounds simple at first, but how would you actually do it?

Use astype() to convert the values to another dtype:

import numpy as np
(a+2**63).astype(np.uint64)
# array([                   0, 18446744073709551615], dtype=uint64)

I'm not a real numpy expert, but this:

>>> a = np.array([-2**63,2**63-1], dtype=np.int64)
>>> b = np.array([x+2**63 for x in a], dtype=np.uint64)
>>> b
array([                   0, 18446744073709551615], dtype=uint64)

works for me with Python 2.6 and numpy 1.3.0

I assume you meant 2**64-1 , not 2**64 , in your expected output, since 2**64 won't fit in a uint64. (18446744073709551615 is 2**64-1 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM