0

How exactly do the V and S flags function on the ATMEGA328?

The ATMEGA328 has separate sign (S), carry (C), 2's complement overflow (V) and negative (N) flags. N is the MSB (corresponding to the sign bit on other processors). How exactly the V flag operates is not well explained in the datasheet. As I understand it, V is generally calculated as N⊕C. But S is defined in the datasheet as V⊕N which implies that it equals N⊕N⊕C or just C. If that's true then it doesn't make much sense to have a separate flag for it so I suspect I've misunderstood something here.

sprinter
  • 27,148
  • 6
  • 47
  • 78
  • When I looked at the ADC (Add with Carry) instruction, it explained what V meant and gave the boolean formula for it. Is there some other AVR instruction for which you think V is not documented well? You could ask a new question about that instruction. – David Grayson Apr 27 '22 at 00:48

1 Answers1

0

V is not generally the same as N XOR C.

I found a counterexample by looking at the ADC (Add with Carry) instruction in the manual and considering what would happen if you add 0xFF to 0x02 to get 0x01.

  • C would be 1 because 0xFF + 0x02 = 0x101, which is larger than 0xFF, so there is a carry from the most significant bit of the addition.
  • N would be 0 because it is simply the MSB of the result.
  • V would be 0 because it is defined to be 1 if two's complement overflow happened. From the perspective of two's complement, we simply added -1 and 2 to get 1, so there is no overflow. And you can confirm this by carefully evaluating the formula in the manual to calculate V.
David Grayson
  • 84,103
  • 24
  • 152
  • 189
  • Thankyou that explained it very well. I had made 2 mistakes: firstly, I was not aware of the instruction set manual you linked: I was using the 328's datasheet which gives very little detail on the supported instruction. The instruction set manual is very helpful. Secondly, I found the N⊕C from https://stackoverflow.com/questions/32805087/how-is-overflow-detected-in-twos-complement but hadn't realised that this only works if the two operands have the same sign. Once you add that condition you end up with precisely the formula in the manual. Thanks for the help. – sprinter Apr 27 '22 at 09:44