1

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.

0

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.