以下是针对 64 位机器测试的。如果您有 32 位机器,请卸下 64 位齿轮,并更改 flag64 -> flag32 (并使用pushfd
代替pushfq
)。在实践中,我发现我只需要检查标志寄存器中的 CY(进位)和 OV(溢出)(我通常使用jc
、jnc
、jo
和jno
)。
#include <stdio.h>
#include <stdint.h>
#define HIGH32(x) ((uint32_t)(((uint64_t)x)>>32))
#define LOW32(x) ((uint32_t)(((uint64_t)x)& 0xFFFFFFFF))
int main(int argc, char** argv)
{
uint32_t eax32, ebx32, ecx32, edx32;
uint64_t rax64, rbx64, rcx64, rdx64;
asm (
"movl %%eax, %[a1] ;"
"movl %%ebx, %[b1] ;"
"movl %%ecx, %[c1] ;"
"movl %%edx, %[d1] ;"
"movq %%rax, %[a2] ;"
"movq %%rbx, %[b2] ;"
"movq %%rcx, %[c2] ;"
"movq %%rdx, %[d2] ;"
:
[a1] "=m" (eax32), [b1] "=m" (ebx32), [c1] "=m" (ecx32), [d1] "=m" (edx32),
[a2] "=m" (rax64), [b2] "=m" (rbx64), [c2] "=m" (rcx64), [d2] "=m" (rdx64)
);
printf("eax=%08x\n", eax32);
printf("ebx=%08x\n", ebx32);
printf("ecx=%08x\n", ecx32);
printf("edx=%08x\n", edx32);
printf("rax=%08x%08x\n", HIGH32(rax64), LOW32(rax64));
printf("bax=%08x%08x\n", HIGH32(rbx64), LOW32(rbx64));
printf("cax=%08x%08x\n", HIGH32(rcx64), LOW32(rcx64));
printf("dax=%08x%08x\n", HIGH32(rdx64), LOW32(rdx64));
uint64_t flags;
asm (
"pushfq ;"
"pop %[f1] ;"
:
[f1] "=m" (flags)
);
printf("flags=%08x%08x", HIGH32(flags), LOW32(flags));
if(flags & (1 << 0)) // Carry
printf(" (C1");
else
printf(" (C0");
if(flags & (1 << 2)) // Parity
printf(" P1");
else
printf(" P0");
if(flags & (1 << 4)) // Adjust
printf(" A1");
else
printf(" A0");
if(flags & (1 << 6)) // Zero
printf(" Z1");
else
printf(" Z0");
if(flags & (1 << 7)) // Sign
printf(" S1");
else
printf(" S0");
if(flags & (1 << 11)) // Overflow
printf(" O1)\n");
else
printf(" O0)\n");
return 0;
}