将 int[2] 转换为 long
我在 32 位机器上有一个 long int 的 int[2] 表示形式,并希望在 64 位机器上将其转换为 long 。是否有一种安全的独立于架构的方法来进行这种转换?
源机器是32位的,int也是32位的。目标机器是64位,long long类型肯定是64位。
我可以执行以下操作吗?
long i;
int j[2];
#ifdef LITTLEENDIAN
j[1] = *(int*)(&i);
j[0] = *(((int*)(&i))+1)
#else
j[0] = *(int*)(&i);
j[1] = *(((int*)(&i))+1)
#endif
如果上述方法不正确,那么最好、最安全的方法是什么?我确信以前会问过这个问题,但我没有找到明确的答案。
谢谢
I have an int[2] representation of a long int in a 32 bit machine and want to convert it to long on 64bit machine. is there a safe architecture independent way of doing this conversion?
The source machine is 32bit and an int is 32bits. Destination machine is 64bit and the long long type is definitely 64bits.
can I do the following?
long i;
int j[2];
#ifdef LITTLEENDIAN
j[1] = *(int*)(&i);
j[0] = *(((int*)(&i))+1)
#else
j[0] = *(int*)(&i);
j[1] = *(((int*)(&i))+1)
#endif
If the above is incorrect, then what is the best and safest way for this? I am sure this would have been asked previously, but I didn't find a clean answer.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
并不真地。因为除了字节序之外,两种数据类型的大小也可能不同。在一些流行的平台上,
int
和long
具有相同大小(均为 32 位)最终,这取决于您创建
的方式int[2]
表示。无论您如何创建该int
数组,都必须反转才能从中获取有效的long
数组。一种在实践中可行的方法(但从技术上讲,是未定义的行为)是将两者放在一个联合中:
现在您可以简单地写入
u.i2
并从ul< /代码>。 C++ 标准在技术上不允许这样做(这是未定义的行为),但这是一个常见的技巧,主要编译器无论如何都明确支持它。
然而,更好的方法可能是使用
char[]
而不是int[]
,因为char
被明确允许别名为其他类型。Not really. Because apart from endianness, the sizes of the two datatypes may vary as well. On some popular platforms,
int
andlong
have the same size (both 32 bits)Ultimately, it depends on how you created your
int[2]
representation. Whatever you did to create thatint
array has to be reversed in order to get a validlong
out of it.One approach which will work in practice (but is, technically speaking, undefined behavior), is to place both in a union:
Now you can simply write to
u.i2
and read fromu.l
. The C++ standard technically doesn't allow this (it is undefined behavior), but it is such a common trick that major compilers explicitly support it anyway.However, a better approach might be to use a
char[]
instead ofint[]
, becausechar
's are explicitly allowed to alias other types.如果您确定拥有 32 位整数和 64 位整数,那么您可以使用
union
概念。If you are sure of having 32-bit integer and 64-bit then you can use
union
concept.宽度问题可以通过在两台机器上使用 boost::uint64_t 来解决。
http:// /www.boost.org/doc/libs/1_46_1/libs/integer/doc/html/boost_integer/cstdint.html#boost_integer.cstdint.exact_width_integer_types
The width concern could be addressed by using boost::uint64_t on both machines.
http://www.boost.org/doc/libs/1_46_1/libs/integer/doc/html/boost_integer/cstdint.html#boost_integer.cstdint.exact_width_integer_types