I am trying to make a function that adds two numbers of any type (float, int, double etc), and saves the result into another number of the same type.
I was looking into void *
and learned that by casting to unsigned char *
, I can get each byte of each number.
The problem I am facing is, that when I add something greater than the range of an unsigned char
, it wraps around. So in my case 255 + 1 = 0
.
This my code so far,
typedef unsigned char byte;
// add two numbers (of any type) of size abc_size and save in c
void add(void *a, void *b, void *c, size_t abc_size) {
byte *a_bytes = (byte *) a;
byte *b_bytes = (byte *) b;
byte *c_bytes = (byte *) c;
for (size_t i = 0; i < abc_size; i++) {
byte a_byte = a_bytes[i];
byte b_byte = b_bytes[i];
byte sum = a_byte + b_byte; // do i have to account for carry or endianess?
c_bytes[i] = sum;
}
}
and the main I used for testing,
#include <stdio.h>
int main(void) {
int a = 255;
int b = 1;
int c = 0;
add(&a, &b, &c, sizeof(int));
printf("%d + %d = %d\n", a, b, c);
}
The output of the above is,
255 + 1 = 0
I am also facing a problem when I am trying to add floats
or doubles
, which the result is completely unexpected, and I would image is again because of the overflow.
Can this method work at all for any number and any type? If so, what do I need to change?
Thank you in advance.