All submissions

Carry Flag in 8-bit Addition

Code

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

void add_with_carry(uint8_t a, uint8_t b, uint8_t* result, uint8_t* carry) {
    // Your logic here
    *result = a + b;
    // handle case where msb of both a/b set
    uint8_t a_msb = a & 0x80;
    uint8_t b_msb = b & 0x80;
    if (!a_msb && !b_msb) {
        *carry = 0;
    } else if (a_msb && b_msb) {
        *carry = 1;
    } else {
        // one of them is set, convert to 7-bit integers and see if 8th bit gets set
        a &= 0x7F;
        b &= 0x7F;
        a = a+b;
        if (a&0x80) {
            *carry = 1;
        } else {
            *carry = 0;
        }
    }
    return;
}

int main() {
    uint8_t a, b, result, carry;
    scanf("%hhu %hhu", &a, &b);

    add_with_carry(a, b, &result, &carry);

    printf("%u ", result);
    printf("%u", carry);
    return 0;
}

Solving Approach

 

 

 

Loading...

Input

100 50

Expected Output

150 0