thevpt
thevpt

Reputation: 51

Emulate c cast operation of float to int in python

I am trying to convert for example: 6.09677e-321 -> 1234 in c you can do something like: printf("%lld", 6.09677e-321) Any ideas of how to get that casting into python?

I've tried with ctypes, d=c_float(6.09677e-321);cast(f, c_longlong) but didn't get much out of it.

Upvotes: 1

Views: 415

Answers (2)

bgporter
bgporter

Reputation: 36564

You can also use the struct module for this:

>>> import struct
# treat the value as a double
>>> packed = struct.pack("d", 6.097e-321)
>>> packed
'\xd2\x04\x00\x00\x00\x00\x00\x00'
# ...but unpack it as a long int
>>> unpacked = struct.unpack("l", packed)
>>> unpacked[0]
1234

Upvotes: 2

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 96277

Python int and float types are not like primitive C numeric types. They are full-fledged objects. Python objects don't really have "casts" in that sense. However, you can do this using ctypes, which essentially provides object-oriented wrappers over primitive C types. It will be a little convoluted though:

import ctypes

py_float = 6.097e-321

cf = ctypes.c_double(py_float)
lp = ctypes.cast(ctypes.pointer(cf), ctypes.POINTER(ctypes.c_int64))

py_int = lp.contents.value
print(py_int) # 1234

Upvotes: 1

Related Questions