Home > Software design >  Getting IEEE754 byte representation from numpy
Getting IEEE754 byte representation from numpy

Time:11-02

Is there a way using numpy to get a hex representation from a floating point value operation? I'd like to avoid strings if at all possible.

for example:

1.1 in single precision hex representation is 0x3F8CCCCD

1.1 in double precision hex representation is 0x3FF199999999999A

Ideally I'd like to be able to do something like:

numpy.function(value)

returns

hex representation

Any good way to do this?

CodePudding user response:

I can write a function that will give you the integer interpretation of the binary representation of the floating points as follows.

def to_words(x):
  ''' Gets the integer interpretation of the IEEE754 binary representation '''
  if x.dtype == np.float32:
    y = np.array(x);
    y.dtype = np.uint32;
    return y;
  elif x.dtype == np.float64:
    y = np.array(x)
    y.dtype = np.uint64;
    return y;

Maybe you can find a way to get the hex representation from there.

CodePudding user response:

Well you could use frombuffer reinterpret the bytes of a float array or scalar as a 1D array of unsigned integers; note that it is a view, not a copy, of the bytes. To get the scalar integer value out of the array (and this does copy the value, not a view), you just index.

x32 = np.frombuffer(np.float32(1.1), dtype = np.uint32)[0]
# 1066192077

x64 = np.frombuffer(np.float64(1.1), dtype = np.uint64)[0]
# 4607632778762754458

To print these unsigned integers as their hex representation, you really do have to explicitly convert it to a string. Avoiding strings when printing isn't really possible. Everything is stored as bytes, 1s and 0s, so numbers are naturally in base-2. The common default of printing in base-10 also requires string conversion from the bytes.

hex(x32)
# '0x3f8ccccd'

hex(x64)
# '0x3ff199999999999a'

CodePudding user response:

You can use the view method of numpy arrays to do the equivalent of a C cast. Another approach is to use float.hex to give a more human-friendly hex representation than shown in the original post.

Example program:

import numpy as np
d = np.array(1.1)
i = d.view('int64')
print(f'double:      {d}')
print(f'cast to int: {i}')
print(f'hex:         0x{i.item():016x}')
print(f'floathex:    {float.hex(d.item())}')

Output:

double:      1.1
cast to int: 4607632778762754458
hex:         0x3ff199999999999a
floathex:    0x1.199999999999ap 0
  • Related