Two's Compliment

z80 » Beginner

To represent negative numbers in binary, there is something called the Two's Compliment. To make a (containing %00000101 or 5) into a negative number, you flip all the 1's to 0's and all the 0's to 1's (%11111010 or 250). But that's not all, you have to add one to get the final -5 (%11111011 or 251). The processor adds 256 (%1 00000000 or $100) to a number to store it as a negative. You will have your calculator's handy base conversion handy so you will only have to understand the basics of this. You will learn a command that does this for you with a later on. Here's some code that will make the number in a negative.

	xor %11111111
	inc a

A command that you haven't learned about yet will do the flipping of all the bits for you: cpl. It does the same thing as xor %11111111 with a.

	cpl
	inc a

There is yet another command that further simplifies this code by nagating the number in a for us: neg.

	neg
These are only neccessary at run-time (while the program is executing). Remember, though, that your assembler does support negative numbers. It will do all these calculations at assembly time.
	ld de,-400
	ld a,-24
	ld hl,-12


More from z80 » Beginner
Aliases // Convert from decimal to hexadecimal or binary // Flags and Conditions // Format and Compiling // Instructions // Math // Number Bases // Oh, No! It Crashed! // Registers // TI-BASIC to Asm Comparisons // TI86 Specifications // Two's Compliment // z80 Processor