Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access the flags without inline assembly?

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

  • 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?

like image 866
Govind Parmar Avatar asked Jan 01 '26 14:01

Govind Parmar


2 Answers

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.

like image 149
harold Avatar answered Jan 03 '26 05:01

harold


You don't need to access the flags to do higher precision arithmetics. There is a carry if the sum is smaller than either of the operands, so you can do like this

short __declspec(naked) getchecksum(short s1, short s2)
{
    short s = s1 + s2;
    if ((unsigned short)s < (unsigned short)s1)
        s++;
    return ~s;
}

There are already many questions about adding and carrying on SO: Efficient 128-bit addition using carry flag, Multiword addition in C

However in C operations are always done at least in int type so you can simply add that if int has more than 16 bits in your system. In your case the inline assembly is 16-bit x86 so I guess you're on Turbo C which should be get rid ASAP (reason: Why not to use Turbo C++?). In other systems that has 16-bit int you can use long which is guaranteed to be at least 32 bits by the standard

short __declspec(naked) getchecksum(short s1, short s2)
{
    long s = s1 + s2;
    return ~((s & 0xffff) + ((s >> 16) & 0x1));
}
like image 33
phuclv Avatar answered Jan 03 '26 04:01

phuclv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!