gpt4 book ai didi

python - 什么是 CPP reinterpret_cast 的 Python 等价物

转载 作者:行者123 更新时间:2023-11-28 20:33:02 30 4
gpt4 key购买 nike

我陷入了 reinterpret_cast 转换运算符的一个小问题。基本上,在 CPP 中,我有一个 float 变量,它用于使用 reinterpret_cast 创建一个 uint32_t 变量,如下所示-

float x = 2.2949836e-38;
uint32_t rgb = *reinterpret_cast<uint32_t*>(&x);
printf("rgb=%d", rgb); // prints rgb=16377550

我想在 python 中实现相同的目标。请注意,传统的 int 转换不会产生预期的结果。

最佳答案

您可以使用 struct 模块中的 packunpack:

from struct import pack, unpack

b = pack('f', 2.2949836e-38)
print(unpack('i', b)[0])

打印:

16377550

编辑:

简化示例

关于python - 什么是 CPP reinterpret_cast 的 Python 等价物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51502600/

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