简体   繁体   English

function 添加 16 位变量

[英]function that adds 16-bit variables

I am writing my first emulator (Intel 8086 microprocessor).我正在编写我的第一个模拟器(英特尔 8086 微处理器)。

I'm stuck because I have to write a function that adds 16-bit variables together.我被卡住了,因为我必须编写一个将 16 位变量加在一起的 function。 Here is the prototype of the function I want to write:下面是我要写的function的原型:

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: function 应该这样计算:

              111
  0000000000000101 (= 5)
+ 0000000000000011 (= 3)
  ----------------
              1000 (= 8)

and return 8.并返回 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.为了编写这个 function,我需要找到一种方法来访问这两个变量的每一位,然后能够将它们加在一起并将它们放在第三个变量中。

Is this possible in C and if so can someone enlighten me on this?这在 C 中是否可能,如果是这样,有人可以启发我吗?

Thank you very much for your answers.非常感谢您的回答。

Assuming 32 bit computer, this is very trivial:假设是 32 位计算机,这很简单:

#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.其中reg + operand将提升为 32 位int ,如果加法超过 16 位,则 boolean 标志将设置为 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如果你想得到第 n 位(第 0 位是最低有效位,第 16 位是最高有效位),你可以这样做

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.它的作用是右移n位,所以你想要的位是最低有效位,然后它会做一个位掩码来只得到那个位。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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