【问题标题】:Difficult cast with int64 and int32 pointers使用 int64 和 int32 指针进行困难转换
【发布时间】:2016-08-03 23:52:43
【问题描述】:
我有int64_t value1; int32_t value2;。然后我有*(int32_t*)&value1 = value2;
您能否描述一下*(int32_t*)&value1 的含义?是不是表示“value1 的最低 32 位”所以*(int32_t*)&value1 = value2; 表示“value1 的前 32 位被 value2 的那些替换”?
还是我完全错了?
【问题讨论】:
标签:
pointers
casting
int
memory-address
【解决方案1】:
这将取决于运行它的机器的字节顺序。这是非常糟糕的做法。
在大多数 Intel 硬件的 little endian 系统上,最低字节在前,因此 32 位 SIGNED 值将写入 64 位整数的低 32 位。在大端系统上,它将被写入高位。
注意 int 是有符号的。如果 value2 是负值,则生成的 64 位数字将不是负数(除非它已经是负数)。
它也不会改变 64bit int 的高位。
我会说...不要那样做?
编辑
为了更直接地回答您的问题,是的,您是对的,这取决于您所说的“前 32 位”是什么意思。首先,无论平台使用什么顺序,都可以。
&value1 -> will give the address of value1
(int32_t*)&value1 -> tells the compiler to treat the address of value1 as a pointer to an int32_t
*(int32_t*)&value1 -> then dereference the pointer, so assigning to this will put the assigned value into the address of value1 as if it were an int32_t.