简体   繁体   中英

function that adds 16-bit variables

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.

You very roughly need something like this:

#include <stdio.h>
#include <stdint.h>

int carry = 0;

uint16_t add(uint16_t reg, uint16_t operand)
{
  uint32_t result = (unint32_t)reg + operand;

  carry = 0;
  if (result > 0xffff)
    carry = 1;

  return result &= 0xffff;
}


int main()
{
  uint16_t r1, r2, r3;

  r1 = 0x10;
  r2 = 0x1000;
  r3 = add(r1, r2);
  printf("r3 = %04x, carry = %d\n", r3, carry);

  r1 = 0x11;
  r2 = 0xffff;
  r3 = add(r1, r2);
  printf("r3 = %04x, carry = %d\n", r3, carry);
}

Adapt it to your needs.

If you want to get the nth bit (the 0th bit is the least significant bit, the 16th bit is the most significant bit), you can do

uint8_t bit = (num >> n) & 1;

What this does is it right shifts the number n bits, so the bit you want is the least significant bit, then it does a bitmask to only get that bit.

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