[英]Equivalent of C++ union in Python
Say I have the following code in C++: 假设我在C ++中有以下代码:
union {
int32_t i;
uint32_t ui;
};
i = SomeFunc();
std::string test(std::to_string(ui));
std::ofstream outFile(test);
And say I had the value of i
somehow in Python, how would I be able to get the name of the file? 并说我在Python中有某种价值,
i
怎么能得到文件的名称?
For those of you that are unfamiliar with C++. 对于那些不熟悉C ++的人。 What I am doing here is writing some value in
signed
32-bit integer format to i
and then interpreting the bitwise representation as an unsigned
32-bit integer in ui
. 我在做什么在这里写一些价值
signed
的32位整数格式来i
再解释逐位表示为unsigned
的32位整数ui
。 I am taking the same 32 bits and interpreting them in two different ways. 我采用相同的32位并以两种不同的方式解释它们。
How can I do this in Python? 我怎么能用Python做到这一点? There does not seem to be any explicit type specification in Python, so how can I reinterpret some set of bits in a different way?
Python中似乎没有任何明确的类型规范,那么如何以不同的方式重新解释某些位?
EDIT: I am using Python 2.7.12 编辑:我使用的是Python 2.7.12
I would use python struct for interpreting bits in different ways. 我会使用python结构以不同的方式解释位。
something like following to print -12 as unsigned integer 类似于将-12打印为无符号整数
import struct
p = struct.pack("@i", -12)
print("{}".format(struct.unpack("@I",p)[0]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.