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
    uint8_t operand1, operand2, inter1, inter2, inter3;
    *result = 0, *carry = 0;

    for(uint8_t i=0; i<8; i++)
    {
        operand1 = (a >> i) & 1;
        operand2 = (b >> i) & 1;
        inter1 = operand1 ^ operand2;
        *result |= ((inter1 ^ *carry) << i);
        inter2 = operand1 & operand2;
        inter3 = inter1 & *carry;
        *carry = inter3 | inter2;
    }
}

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

 

 

 

Upvote
Downvote
Loading...

Input

100 50

Expected Output

150 0