I am writing my first emulator (Intel 8086 microprocessor).
I'm stuck because I have to write a function that adds 16-bit variables together. Here is the prototype of the function I want to write:
uint16_t add(uint16_t reg, uint16_t operand);
For example, if we execute :
add(5, 3)
The function should do the calculation like this:
111
0000000000000101 (= 5)
+ 0000000000000011 (= 3)
----------------
1000 (= 8)
and return 8.
To write this function, I need to find a way to access each bit of the two variables, then to be able to add them together and place them in a third variable.
Is this possible in C and if so can someone enlighten me on this?
Thank you very much for your answers.
Assuming 32 bit computer, this is very trivial:
#include <stdint.h>
#include <stdio.h>
_Bool carry;
uint16_t add (uint16_t reg, uint16_t operand)
{
carry = (reg + operand) & 0xFFFF0000u;
return reg + operand;
}
int main (void)
{
int sum = add(65535, 1);
printf("%d, CF:%d\n", sum, (int)carry);
}
Where reg + operand
will get promoted to 32 bit int
and in case the addition goes beyond 16 bits, the boolean flag will get set to 1.