I try to convert from gmpy2.mpz to a numpy boolean array, but can't quite get it right. (gmpy2: https://gmpy2.readthedocs.io)
import gmpy2
import numpy as np
x = gmpy2.mpz(int('1'*1000,2))
print("wrong conversion 1")
y = np.fromstring(gmpy2.to_binary(x), dtype=bool) # this is wrong
print(np.sum(y)) # this returns 127 instead of 1000
print("wrong conversion 2")
y = np.fromstring(gmpy2.to_binary(x), dtype=np.uint8)
print(y) # array([ 1, 1, 255 ... 255], dtype=uint8)
y_bool = np.unpackbits(y)
slow_popcount = np.sum(y_bool, dtype=int)
print(slow_popcount) # 1002. should be 1000
print("Fudging an answer. This is wrong as well.")
y = np.fromstring(gmpy2.to_binary(x)[2:], dtype=np.uint8)
# is that slicing [2:] a slow operation?
y_bool = np.unpackbits(y)
print np.sum(y_bool, dtype=int) # 1000
More tests:
np.fromstring(gmpy2.to_binary(gmpy2.mpz(int('1'*64,2))), dtype=np.uint8)
# array([ 1, 1, 255, 255, 255, 255, 255, 255, 255, 255], dtype=uint8)
np.fromstring(gmpy2.to_binary(gmpy2.mpz(int('1'*65,2))), dtype=np.uint8)
# array([ 1, 1, 255, 255, 255, 255, 255, 255, 255, 255, 1], dtype=uint8
np.fromstring(gmpy2.to_binary(gmpy2.mpz(int('1'*66,2))), dtype=np.uint8)
# array([ 1, 1, 255, 255, 255, 255, 255, 255, 255, 255, 3], dtype=uint8)
np.fromstring(gmpy2.to_binary(gmpy2.mpz(int('1'*1024,2))), dtype=np.uint8)
# array([ 1, 1, 255 ... 255], dtype=uint8)
By the way, I actually want to quickly get a list, array, or numpy array of indices of all set bit of a gmpy2.mpz. The actual 4,777,000 gmpy2.mpz that I try to convert each has 760,000 bits with about 2,000 bits of 1. The gmp library on the computer was compiled with intel icc.
Thanks