I am writing some code to deal with numbers in C which are bigger than 8 bytes in size (don't fit into unsigned long
). In this example I will use 16 bytes (128 bits) as the width. The numbers are unsigned and integers (no decimal places). They are stored as an array of unsigned chars eg:
unsigned char n[16];
I have managed to get addition to work (it works like an unsigned number in C so if you had a number which was 0xffffffffffffffffffffffffffffffff
(2**128) and you were to add 1
you would get 0
. I have managed to get addition to work, but I cannot get subtraction to work. I would assume it would be similar code to addition, but I don't seem to be able to get it to work.
Addition code:
//a and b are numbers
unsigned char *add(unsigned char *a, unsigned char *b){
unsigned char *c = malloc(NUM_SIZE);
//d is the carry and c is the output number
unsigned short d = 0;
if(!c){
return NULL;
}
for(int i = 0; i < NUM_SIZE; i++){
c[i] = 0;
}
for(int i = NUM_SIZE * 2 - 1; i >= 0; i--){
d += a[i % NUM_SIZE] + b[i % NUM_SIZE];
c[i % NUM_SIZE] = d % 256;
d >>= 8;
}
return c;
}
NUM_SIZE
is defined as 16 (the width of the number in bytes)
What I have tried:
//changing the signs to minuses
d -= a[i % NUM_SIZE] - b[i % NUM_SIZE];
//changing the some signs to minuses
d -= a[i % NUM_SIZE] + b[i % NUM_SIZE];
//or
d += a[i % NUM_SIZE] - b[i % NUM_SIZE];
//looping through the number backwards
for(int i = 0; i < NUM_SIZE * 2; i++)