简体   繁体   中英

Most efficient method of adding 16-bit numbers, lookup table, binary addition or simple addition?

I am attempting to code the ADD function for an MSP-430 emulator I am attempting to build.

I was wondering if a lookup table for the addition of two 16-bit numbers would be a viable solution for efficient retrieval of my results. Alternative methods I have thought of implementing are a binary addition loop, which adds bits one by one or a simple decimal addition. I need to be able to determine the sign and the carry (if there is one).

Any specs on the micro-controller can be found here .

You can use simple 32-bit, two's-complement arithmetic. Assuming src and dst are stored in the lower 16-bits of a uint32_t , the following code sequence emulates the ADD instruction:

uint32_t xor = src ^ dst;
dst += src;
flags.N = (dst >> 15) & 1;
flags.C = (dst >> 16) & 1;
flags.V = ((~xor & (src ^ dst)) >> 15) & 1;
dst &= 0xFFFF;
flags.Z = (dst == 0);

The result of the addition itself can be obtained by simply taking the lower 16 bits of a 32-bit addition. The N, Z, and C flags are also easy to compute. The (signed) overflow flag V is more tricky. The code basically tests whether the signs of src and dst were equal before the addition and are different afterwards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM