在没有内联汇编的情况下访问标志? [英] Access the flags without inline assembly?

查看:107
本文介绍了在没有内联汇编的情况下访问标志?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C语言中,我有以下方法需要两个16位short int和:

I have the following method in C that takes two 16-bit short ints and:

  • 将两个整数相加
  • 如果设置了进位标志,请在结果中加1
  • 否定(不)最终结果中的所有位
  • 返回结果:

  • Adds the two integers
  • If the carry flag is set, add 1 to the result
  • Negate (NOT) all the bits in the final results
  • Return the result:

short __declspec(naked) getchecksum(short s1, short s2)
{
    __asm
    {
        mov ax, word ptr [esp+4]
        mov bx, word ptr [esp+8]
        add ax, bx
        jnc skip_add
        add ax, 1
        skip_add:
        not ax      
        ret
    }
}

我不得不用内联汇编语言编写此代码,因为如果不使用汇编程序,我不知道有什么方法可以测试进位标志.有人知道这样做的方法吗?

I had to write this in inline assembly because I do not know any way to test the carry flag without using assembler. Does anyone know of a way to do this?

推荐答案

否(C根本没有标志的概念),但这并不意味着您无法获得相同的结果.如果使用32位整数进行加法运算,则第17位为进位.所以你可以这样写:

No (C has no notion of flags at all) but that doesn't mean you can't get the same result. If you use 32bit integers to do addition, the 17th bit is the carry. So you can write it like this:

uint16_t getchecksum(uint16_t s1, uint16_t s2)
{
    uint32_t u1 = s1, u2 = s2;
    uint32_t sum = u1 + u2;
    sum += sum >> 16;
    return ~sum;
}

为了防止麻烦,我将类型设置为无符号.在您的平台上可能没有必要.

I've made the types unsigned to prevent trouble. That may not be necessary on your platform.

这篇关于在没有内联汇编的情况下访问标志?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆