gpt4 book ai didi

Python - 将有符号 float 转换为无符号长整数(win32 为 DWORD)

转载 作者:太空宇宙 更新时间:2023-11-04 15:42:25 25 4
gpt4 key购买 nike

我知道 python 没有无符号变量,但我需要将一个从运行 python ( Blender ) 的程序转换为用 C++ 编写的 win32 应用程序。我知道我可以像这样转换整数:

>>> int i = -1

>>> _ + 2**32

我怎样才能将 float :0.2345f 转换为长整型?我需要在 python 中转换为 long,然后在 win32( c++ ) 中转换回 float...

通常在 C++ 中它下降了

>>>float f = 0.2345f;

>>>DWORD dw = *reinterpret_cast< DWORD* >( &f );

这会产生一个 unsigned long ... 并且将它转换回来只是相反的过程:

>>>FLOAT f = *reinterpret_cast< FLOAT* >( &dw );

最佳答案

您可以为此使用struct.packstruct.unpack。请注意,它不是转换(即对同一内存的重新解释),而是转换器(复制到新内存)。

import struct

def to_float(int_):
return struct.unpack('d', struct.pack('q', int_))[0]

def to_long(float_):
return struct.unpack('q', struct.pack('d', float_))[0]


data = 0.2345
long_data= to_long(data) #4597616773191482474
new_data = to_float(long_data) #0.2345

关于Python - 将有符号 float 转换为无符号长整数(win32 为 DWORD),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21106976/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com