Untitled

mail@pastecode.io avatar
unknown
csharp
4 months ago
2.5 kB
2
Indexable
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <ctype.h>
#include <stdlib.h>
#include "signMag.h"

#define MAX_VAL 65535
#define BAD_VAL 0

SignMag_t signMag_init(bool isNegative, uint16_t magnitude)
{
    SignMag_t num;
    num.isNegative = isNegative;
    num.magnitude = magnitude;
    return num;
}

void signMag_print(SignMag_t value)
{   
    if (value.isNegative) {
        printf("-%hu\n", value.magnitude);
    } else {
        printf("%hu\n", value.magnitude);
    }
}


SignMag_t signMag_read(void)
{
    bool negative = false;
    bool valid = false;
    uint16_t magnitude = 0;
    uint32_t number = 0;

    uint16_t chr = getchar();
    if (chr == '-') {
        negative = true;
        chr = getchar();
    } else if (chr == '+') {
        negative = false;
        chr = getchar();
    } else if (!isdigit(chr)) {
        return signMag_init(true, 0);
    }

    while (isdigit(chr)) {
        number = (magnitude * 10) + (chr - '0');
        if (number > MAX_VAL) {
            magnitude = MAX_VAL;
        } else {
            magnitude = number;
        }       
        chr = getchar();
        valid = true;
    }

    return valid ? signMag_init(negative, magnitude) : signMag_init(true, 0); // change

}

SignMag_t signMag_sum(SignMag_t sm1, SignMag_t sm2)
{
    bool isNegative = false;
    uint16_t magnitude = 0;
    uint32_t totalSize = 0;
    uint16_t num1Size = sm1.magnitude;
    uint16_t num2Size = sm2.magnitude;
    
    if (sm1.isNegative == sm2.isNegative) {
        isNegative = sm1.isNegative;
        totalSize = (num1Size + num2Size);
        magnitude = totalSize;
    } else if (sm1.isNegative != sm2.isNegative) {
        isNegative = (num1Size > num2Size) ? (sm1.isNegative) : (sm2.isNegative);
        if (isNegative == sm1.isNegative) {
            totalSize = (num1Size - num2Size);
        } else {
            totalSize = (num2Size - num1Size);
        }
        magnitude = totalSize;
    }

    if (totalSize == 0) {
        return signMag_init(false, 0);
    }

    return (totalSize < MAX_VAL) ? signMag_init(isNegative, magnitude) : signMag_init(isNegative, MAX_VAL);
    
}

SignMag_t signMag_accumulate(const SignMag_t* array, size_t arraySize)
{
    bool isNegative = array[0].isNegative;
    uint16_t magnitude = array[0].magnitude;
    SignMag_t num = {isNegative, magnitude};
    for (size_t i = 1; i < arraySize; i++)
    {
        num = signMag_sum(num, array[i]);
    }

    return num;
}
Leave a Comment