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
    uint8_t carry_flag = 0;
    uint8_t shift = 0;
    uint8_t tmp_result = 0;
    *result = 0;
    *carry = 0;

    do {
        uint8_t tmp_sum = a & 0x01;
        tmp_sum += b & 0x01;
        tmp_sum += carry_flag;

        uint8_t tmp_bit = tmp_sum % 2;
        carry_flag = tmp_sum >= 2;
        *result |= (tmp_bit << shift);
        
        ++shift;
        a >>= 1;
        b >>= 1;
    } while (a || b);


    if (shift >= 8) {
        *carry = carry_flag;
    } else if (carry_flag) {
        *result |= (1 << shift);
    }
}

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