CandyGum
CandyGum

Reputation: 511

Float Pointer to Hexadecimal

The code I use to convert hexadecimals > float pointers:

from ctypes import *

def convert(s):
    i = int(s, 16)                   # convert from hex to a Python int
    cp = pointer(c_int(i))           # make this into a c integer
    fp = cast(cp, POINTER(c_float))  # cast the int pointer to a float pointer
    return fp.contents.value         # dereference the pointer, get the float

print convert("41973333")    # returns 1.88999996185302734375E1

print convert("41995C29")    # returns 1.91700000762939453125E1

print convert("470FC614")    # returns 3.6806078125E4

But I am not sure how I could reverse this effect, so to say.

I'm trying to go from float pointer > hexadecimal, instead of hexadecimal > float pointer.

Upvotes: 0

Views: 599

Answers (2)

ankur09011
ankur09011

Reputation: 473

You can use struct to convert hex to float

import struct

struct.unpack('!f', '41995C29'.decode('hex'))[0]

will give:

19.170000076293945

Upvotes: 0

Aran-Fey
Aran-Fey

Reputation: 43196

You do the same thing, but backwards:

  1. Cast the float to an int
  2. Convert the int to hex

The code:

def float_to_hex(x):
    fp = pointer(c_float(x))
    ip = cast(fp, POINTER(c_int))
    x = ip.contents.value
    return '{:02X}'.format(x)

Output:

>>> float_to_hex(1.88999996185302734375E1)
'41973333'
>>> float_to_hex(1.91700000762939453125E1)
'41995C29'
>>> float_to_hex(3.6806078125E4)
'470FC614'

Upvotes: 1

Related Questions