2

I see that in x86 CPUs, the parity flag (PF) is set when the number of bits set to 1 is even, and that only the first byte (lower 8 bits) of a value are ever tested.

The only case I am not sure about is when we are dealing with a value of 0.

I have seen at least other question where the parity flag seems to be set to 1 for a value of 0.

For instance, for the value 8000h the lower 8 bits are all 0, and the parity flag is said to be set to 1.

So, shall I accept that for 0 bits set to 1, the parity flag gets enabled, just like for an even number of bits set to 1?

alt.126
  • 1,097
  • 1
  • 9
  • 22

1 Answers1

6

0 has an even number of bits, so, the answer is yes.

Test:

// compiled with Open Watcom C/C++ 1.9
#include <stdio.h>

unsigned parity(unsigned v)
{
  unsigned p = 0;
  __asm
  {
    mov eax, v
    or  eax, eax
    pushf
    pop eax
    shr eax, 2
    and eax, 1
    mov p, eax
  }
  return p;
}

int main(void)
{
  unsigned i;
  for (i = 0; i < 8; i++)
    printf("PF(%u) = %u\n", i, parity(i));
  return 0;
}

Output:

PF(0) = 1
PF(1) = 0
PF(2) = 0
PF(3) = 1
PF(4) = 0
PF(5) = 1
PF(6) = 1
PF(7) = 0
zneak
  • 134,922
  • 42
  • 253
  • 328
Alexey Frunze
  • 61,140
  • 12
  • 83
  • 180
  • 1
    You might want to tweak the first line of your answer, 2 is an even number as well. It is the number of bits set to 1 that matters. – Hans Passant Apr 11 '13 at 23:24
  • 1
    @HansPassant I think the three of us understand it. – Alexey Frunze Apr 11 '13 at 23:30
  • That is just about the least efficient way you could code the asm for `parity()`. `cmp [v], 0` / `setp byte ptr [p]` should do the trick. Or load it with `mov` and `test eax,eax`. But remember that PF is only set from the low byte of the value, even with a 32-bit `test` or `cmp`.) – Peter Cordes Nov 21 '17 at 03:58
  • Even without using `setp`, you could use `lahf` and that would still be more efficient than `pushf` / `pop eax`. (`pushf` is 3 uops on Haswell for example. But it's not nearly as bad as `popf`, because reading IF, DF, and other EFLAGS bits besides the condition codes is a lot cheaper than writing them). – Peter Cordes Nov 21 '17 at 03:58