Amit Sharma
Amit Sharma

Reputation: 2067

how to copy float32 value to uint64 container using numpy

I want to write any given value in temp to float32, and then store this float value in uint64 container.

value =  np.array(temp, dtype=np.float32, ndmin=1) //works fine
data_f_value = np.frombuffer(value, dtype='uint64') //ValueError: buffer size must be a multiple of element size

I get ValueError and it's expected, but how we can do this operation using numpy ?

Upvotes: 0

Views: 188

Answers (1)

Stef
Stef

Reputation: 30589

IIUC you're looking for a view. Example with the value 0.15625 from Wikipedia:

import numpy as np
value =  np.array([0.15625], dtype=np.float32)
data_f_value = value.view(np.uint32).astype(np.uint64)
#array([1042284544], dtype=uint64)
print(' '.join(f'{x:016b}' for x in  value.tobytes()))
print(' '.join(f'{x:016b}' for x in  data_f_value.tobytes()))

Output:

0000000000000000 0000000000000000 0000000000100000 0000000000111110
0000000000000000 0000000000000000 0000000000100000 0000000000111110 0000000000000000 0000000000000000 0000000000000000 0000000000000000

As the name suggests, this returns a view. If you want to copy as per your question title you'd need value.view(np.uint32).astype(np.uint64).copy().

Upvotes: 1

Related Questions