English 中文(简体)
可以使用一个指针, 与 Python 的浮点数变量的 Int 值匹配吗?
原标题:It is possible to use a pointer that just match the int value from a float variable in Python?

指针在 Python 中并不常见, 无论是 var 声明类型 。 在 Python 中, 我非常适合这样做 。

C++ :

 ...a function
 flt32 f;
 int32 sign, exp, man, *tms;
 tms = (int *) &f;
 ...(operations)
 *tms = sign | exp | man;
 return (f);

如您所见, tms 指向 f 数据,但仅指向 unt 部分(btw,此函数运作良好)。

用这种类型,我可以用 Python 的指针:

from ctypes import * 
f = c_float(12.3)
tms = pointer(f) # tms should be: tms = c_int32(value)
print tms.contents.value #12.3000001907

The problem here is that tms becomes instantly the type of f, so both variables are float (tms should be tms = c_int32(a_value)).
It is possible to use a pointer that just matches the int value from a float variable in Python?

最佳回答

如果您真的想要在 Python 中这样做, 您可以使用 ctype.cast () 来将浮标指针投到 int 指针上, 或者您可以使用 strutct 将浮标值打包到字符串中, 并将其解包到 Int 中 。 这里举一个例子 :

I 使用 ctypes. cast () 来查看浮点数内存, 并使用 strutct 将其转换回 :

In [5]: from ctypes import *
In [6]: f = c_float(12.3)
In [8]: tmp = cast(pointer(f), POINTER(c_int)) 
In [9]: tmp.contents
Out[9]: c_long(1095027917)
In [10]: tmp.contents.value
Out[10]: 1095027917
In [11]: hex(tmp.contents.value)
Out[11]:  0x4144cccd 

In [13]: import struct
In [16]: struct.unpack("f",struct.pack("I", 1095027917))
Out[16]: (12.300000190734863,)
问题回答

要获得浮点数的整数部分, 您需要什么? 只要这样做, 那么 :

i = int(afloat)




相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?