MottZilla wrote:I believe the idea was that, if you have an 8bit value and you are adding a number to it, if the number you end up with is less than wht you started with, then you wrapped around. However when I went back to my original code which does it with an int and a >0xff, it is working again. I guess I was thinking by adding a bunch of 8bit values together it would wrap and never be greater than 0xff. I dunno. I'm tired I guess. :p Thanks for pointing that out. Anyway, I took my newer code and fixed that fuckup. Everything is fine now.
What happened to you there, is that in C/C++ when you do arithmetic on integer types smaller than int, they get promoted to int to do the arithmetic. So its exactly like hap said.
Code: Select all
if( (CPU_A + Value + Carry ) < CPU_A) // Check if Carry will Result
In this case, CPU_A, Value and Carry get promoted to ints. When it adds them together, it's adding three ints and the result is an int. Then its comparing int < CPU_A, again with int on both sides. To really compare an 8-bit value to CPU_A, you would have to cast the thing on the left to an 8-bit type. I think it would still get promoted back to int to do the comparison, but it would only have the bottom 8 bits set.
Its important to remember the rule about small integer types getting promoted to int before doing math on them, because you can get surprised if you do something like this:
Code: Select all
short X = (myShort1 + myShort2) >> 2;
If you expected it to add two 16-bit values and then SHR a 16-bit value and store it in the 16-bit variable... that's not what happens. Both the add and the shift promote their arguments to int, so any carry into bit 16 of the add will end up in bit 14 of your result.
[Edit:
I found this PDF with google. It has some good slides describing how integer promotions work, and some surprising consequences. e.g. if you have an unsigned char C = 0x55, and you write ~C then what you actually get is a very large negative *signed* int! If you then assign it to an unsigned char variable, nothing bad will happen--but I wouldn't recommend doing arithmetic with that value unless you completely understand the integer promotion rules.

]