[英]Is it guaranteed that intptr_t safely roundtrips through uintptr_t?
Can I take an intptr_t
and assign or memcpy it to a uintptr_t
and back again and be guaranteed to end up with the same value?我可以获取一个
intptr_t
并将其分配或 memcpy 到一个uintptr_t
并再次返回并保证最终得到相同的值吗?
That is, are either of the following guaranteed to work (no assert):也就是说,以下任何一项都可以保证工作(无断言):
Using assignment:使用赋值:
intptr_t i1 = f();
uintptr_t u = i1;
intptr_t i2 = u;
assert(i1 == i2);
Using memcpy
:使用
memcpy
:
intptr_t i1 = f();
uintptr_t u;
memcpy(&u, &i1, sizeof(u));
memcpy(&i2, &u, sizeof(u));
assert(i1 == i2);
If it is not guaranteed by the standard, it is possible to check a condition at compile or runtime to determine whether it is guaranteed on a particular platform.如果标准不保证,则可以在编译或运行时检查条件以确定它是否在特定平台上得到保证。
The memcpy
is guarenteed to work, as it treats the values as a sequence of bytes. memcpy
保证工作,因为它将值视为字节序列。 The assignment is not guarenteed to work, though will generally work on any machine that uses 2s complement integers.该分配不能保证工作,但通常可以在任何使用 2s 补码整数的机器上工作。 A machine that uses 1s complement or sign-magnitude will change the value of -0 to 0, though the assert will still be ok, since -0 == 0 is true.
使用 1s 补码或符号幅度的机器会将 -0 的值更改为 0,尽管断言仍然可以,因为 -0 == 0 为真。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.