## Negative numbers

Negative numbers are surprisingly complicated when working in assembler, firstly there is no minus sign inside the registers just 0s and 1s and when is a negative number actually a negative number?

Well it comes down to context so lets look at some examples.

An 8bit register or memory location can hold numbers from 0 - 255 ($00 - $ff) and these numbers are all positive.

But let’s look at an example:

lda #0

sec

sbc #1

We set a = 0 and subtract 1 from it from it, so a now equals -1 but if you look at the value of a in a debugger you will see its set to $ff or 255! But also the negative is set, so does that mean 0 - 1 = -255?

Well no, when working with signed numbers computer use a system called 2's complement. With 2 complement we can represent numbers from -128 to +127. Bit 7 becomes a sign bit so numbers starting with a 1 are positive and numbers starting with a 0 are positive.

I don't want to go too deeply into this for the time being as its not really that relevant to games development on the platform, but if I get any feed back to suggest that this is a topic worth a deep dive I may reconsider. There is plenty of information on the internet on this subject and I really don't want to repeat what many other people have done already.

## No comments:

## Post a Comment