I am writing a program c. I have an unsigned integer (16 bits) whose value can be any at any time, and I have a signed char (8 bits) whose value can be any at any time, within the obvious limits of data types. I need to add a signed char to an unsigned int, the result will be unsigned int, and if the value overflows either past 0xFFFF or below 0x00, I need the result to equal the limit (either 0x00 or 0xFFFF). I want to know what would be the fastest way to do this? My approach is shown below, but it uses a long data type and therefore long binary arithmetic, so I assume there is a faster way ...
long i; unsigned int result; i = someUINT + someCHAR; if(i <= 0) { result = 0; } else if(i >= 0xFFFF) { result = 0xFFFF; } else { result = (unsigned int)i; }
EDIT: I am using a 16-bit MCU (PIC24HJ series) and the Microchip C30 compiler.
source share