在我开发各种版本的代码时,其他人基本上陈述了我在下面展示的相同内容。
我认为您的代码在 32 位版本上运行的原因是侥幸。显然在那个系统上,你未初始化的 mask_val 恰好为零,你是“幸运的”。
下面我展示了您自己的代码的三个版本的进展。首先显示代码基本未更改,但将 mask_val 初始化为 0,并为您希望代码运行的任何类型使用 typedef。第二个是相同的,但没有 BIT[] 表。第三消除循环。
#if 0
#include <stdio.h>
typedef long long valTy;
int main()
{
static unsigned int BIT[] = {
0x1, 0x2, 0x4, 0x8,
0x10, 0x20, 0x40, 0x80,
0x100, 0x200, 0x400, 0x800,
0x1000, 0x2000, 0x4000, 0x8000,
0x10000, 0x20000, 0x40000, 0x80000,
0x100000, 0x200000, 0x400000, 0x800000,
0x1000000, 0x2000000, 0x4000000, 0x8000000,
0x10000000, 0x20000000, 0x40000000, 0x80000000
};
valTy val1, val2;
valTy mask_val;
int i, nbits[2];
printf("\n");
nbits[0] = nbits[1] = 2;
val1 = -41;
val2 = -45;
printf(" val1 = 0x%016llx (%lld)\n", (long long)val1, (long long)val1);
printf(" val2 = 0x%016llx (%lld)\n", (long long)val2, (long long)val2);
printf("\n");
mask_val = 0;
for (i = nbits[0]; i <= nbits[1]; i++)
mask_val = mask_val|BIT[i];
printf("mask_val = 0x%016llx\n\n", (long long)mask_val);
val1 = (val1 & mask_val) >> nbits[0];
val2 = (val2 & mask_val) >> nbits[0];
printf(" val1 = 0x%016llx (%lld)\n", (long long)val1, (long long)val1);
printf(" val2 = 0x%016llx (%lld)\n", (long long)val2, (long long)val2);
printf("\n");
}
#endif
#if 0
#include <stdio.h>
typedef long long valTy;
#define BIT(bitnum) (1<<bitnum)
int main()
{
valTy val1, val2;
valTy mask_val;
int i, nbits[2];
printf("\n");
nbits[0] = nbits[1] = 2;
val1 = -41;
val2 = -45;
printf(" val1 = 0x%016llx (%lld)\n", (long long)val1, (long long)val1);
printf(" val2 = 0x%016llx (%lld)\n", (long long)val2, (long long)val2);
printf("\n");
mask_val = 0;
for (i = nbits[0]; i <= nbits[1]; i++)
mask_val = mask_val | BIT(i);
printf("mask_val = 0x%016llx\n\n", (long long)mask_val);
val1 = (val1 & mask_val) >> nbits[0];
val2 = (val2 & mask_val) >> nbits[0];
printf(" val1 = 0x%016llx (%lld)\n", (long long)val1, (long long)val1);
printf(" val2 = 0x%016llx (%lld)\n", (long long)val2, (long long)val2);
printf("\n");
}
#endif
#include <stdio.h>
typedef long long valTy;
#define BIT(bitnum) (1<<bitnum)
int main()
{
valTy val1, val2;
valTy mask_val;
int i, nbits[2];
printf("\n");
nbits[0] = nbits[1] = 2;
val1 = -41;
val2 = -45;
printf(" val1 = 0x%016llx (%lld)\n", (long long)val1, (long long)val1);
printf(" val2 = 0x%016llx (%lld)\n", (long long)val2, (long long)val2);
printf("\n");
mask_val = 0;
{
valTy maskTop = ((BIT(nbits[0])-1)<<1)|1;
valTy maskBottom = BIT(nbits[1])-1;
mask_val = maskTop & ~maskBottom;
}
printf("mask_val = 0x%016llx\n\n", (long long)mask_val);
val1 = (val1 & mask_val) >> nbits[0];
val2 = (val2 & mask_val) >> nbits[0];
printf(" val1 = 0x%016llx (%lld)\n", (long long)val1, (long long)val1);
printf(" val2 = 0x%016llx (%lld)\n", (long long)val2, (long long)val2);
printf("\n");
}