目标是得到 (-1) 作为最终结果。
#include <stdio.h>
#include <stdint.h>
int main()
{
uint32_t us32Var1, us32Var2;
int32_t s32Var1;
int64_t s64Var1;
us32Var1 = 0;
us32Var2 = 1;
printf("(1) us32Var1 = %u(0x%08x), us32Var2 = %u(0x%08x)\n", us32Var1, us32Var1, us32Var2, us32Var2);
s32Var1 = us32Var1 - us32Var2; //0xffffffff (-1)
printf("(2) s32Var1 = us32Var1 - us32Var2, s32Var1 = %d(0x%08x)\n", s32Var1, s32Var1);
s64Var1 = us32Var1 - us32Var2; //0x00000000ffffffff (expect it's -1, but the result > 0)
printf("(3) s64Var1 = us32Var1 - us32Var2, s64Var1 = %ld(0x%016lx)\n", s64Var1, s64Var1);
s64Var1 = (int64_t)(us32Var1 - us32Var2); //0x00000000ffffffff (expect it's -1, but the result > 0)
printf("(4) s64Var1 = (int64_t)(us32Var1 - us32Var2), s64Var1 = %ld(0x%016lx)\n", s64Var1, s64Var1);
s64Var1 = (int64_t)us32Var1 - us32Var2; //0xffffffffffffffff (-1)
printf("(5) s64Var1 = (int64_t)us32Var1 - us32Var2, s64Var1 = %ld(0x%016lx)\n", s64Var1, s64Var1);
us32Var1 = -1; //us32Var1 = 0xffffffff, UINT32_MAX
s64Var1 = (int64_t)us32Var1; //0x00000000ffffffff (expect it's -1, but the result > 0)
printf("(6) s64Var1 = (int64_t)us32Var1, s64Var1 = %ld(0x%016lx)\n", s64Var1, s64Var1);
s64Var1 = (int32_t)us32Var1; //0xffffffffffffffff (-1 !)
printf("(7) s64Var1 = (int32_t)us32Var1, s64Var1 = %ld(0x%016lx)\n", s64Var1, s64Var1);
return 0;
}
对于上面的程序(每行都有编号),有人可以解释一下吗
- 为什么(2)按预期工作,而不是(3)?ALU 的算术或微步是什么?
- (4) 和 (5) 有什么区别
- 为什么(7)有效而(6)失败