Skip to main content

Binary Arithmetic

At the assembly level, everything is just binary. It helps to know how binary arithmetic works and how it handles different cases.

carry-out and carry-in
  • carry-out is the carry value send out to the next position.
  • carry-in is the carry value received from the previous position.

This means, what's carry-out for one position is the carry-in for the next position.

Status Flags

  1. Carry Flag (CF) - It's set when addition carries out of the most significant bit (MSB), or subtraction needs a borrow. It shows the result is past the max value for the given bits.

  2. Zero Flag (ZF) - This flag is set when the result of an operation is zero. It indicates that the operands were equal in a comparison operation.

  3. Sign Flag (SF) - It's set from the sign of the result. It mirrors the result's MSB. A 0 means positive, a 1 means negative. It's just a copy of the MSB. No special calculation is done for it.

  4. Overflow Flag (OF) - It's set when a signed result is past the range for the given bits. It shows the result is too large or too small to represent.

MSB value

In signed math, the MSB doesn't only set the sign. The MSB also adds to the value, but as a negative amount.

For binary 10001001000100,the value is calculated as 27+0+0+0+0+22+0+0=124-2^7 + 0 + 0 + 0 + 0 + 2^2 + 0 + 0 = -124

Small integers in CPU registers

Working with small integers in exact bit widths is tricky. Registers are always 32 or 64 bits. Say you want a max value of 15 (4 bits). The overflow just uses the other bits in the register.

We use an AND with the exact bits we want to keep. This filters out the unwanted bits.

RFLAG register

RFLAG register is a single register which contains all the status flags. Each flag is represented by a specific bit in this register.

Signed and unsigned calculations

For every operation, the CPU gives both signed and unsigned results. The caller picks the one it needs.

The CPU also sets the result and the CF and OF flags for both.

Java uses only signed

For example, Java has only signed integer types. When Java does arithmetic, it uses the Overflow Flag (OF) to spot overflow in signed math.

How hardware detects these flags

Overflow - It checks the sign bits of the inputs. If both inputs are negative, the output sign bit can't be positive. If both are positive, it can't be negative.

Carry - Checks directly if the last bit's addition has a carry-out of 1. For subtraction, it checks if borrow is needed.

Mental model for carry and overflow

For signed numbers, picture the sequence as a ring. On overflow, the result wraps to the negative side of the ring. This is why it's called an overflow.

For unsigned numbers, picture the sequence as a straight line. On a carry, the result goes past the max limit.

Cases where both carry and overflow happens.

In some cases, with certain mixes of negative and positive numbers, both carry and overflow happen at once.

carry-overflow-mental-model