This repository was archived by the owner on Apr 9, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsum-by-adders.c
More file actions
65 lines (56 loc) · 1.3 KB
/
sum-by-adders.c
File metadata and controls
65 lines (56 loc) · 1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
uint8_t xor(uint8_t x, uint8_t y) {
return (x || y) && (!(x && y));
}
typedef struct {
uint8_t out, carry;
} AdderResult;
AdderResult halfAdder(uint8_t x, uint8_t y) {
AdderResult res = {xor(x, y), x && y};
return res;
}
AdderResult fullAdder(uint8_t x, uint8_t y, uint8_t carry) {
AdderResult r;
r.carry = ((x || y) && carry) || ((x || carry) && y);
r.out = xor(xor(x, y), carry);
return r;
}
const char *toBinary(uint8_t dec);
uint8_t add(uint8_t x, uint8_t y) {
const char *xB = toBinary(x);
const char *yB = toBinary(y);
char bin[] = "00000000";
AdderResult res = halfAdder(xB[7] - 48, yB[7] - 48);
bin[7] += res.out;
for (int i = 6; i >= 0; i--) {
res = fullAdder(xB[i] - 48, yB[i] - 48, res.carry);
bin[i] += res.out;
}
uint8_t out = 0;
for (int i =0; i < 8; i++) {
out *= 2;
out += bin[i] - 48;
}
free((void *)xB);
free((void *)yB);
return out;
}
int main(int argc, char *argv[]) {
uint8_t adderUse = add(0xa, 6);
printf("10 + 6 = %d %b\n", adderUse, adderUse);
return 0;
}
const char *toBinary(uint8_t dec) {
char bin[] = "00000000";
for (int i = 7; i >= 0; i--) {
bin[i] = (char)(48 + (dec % 2));
dec /= 2;
}
char *out = malloc(sizeof(char[9]));
for (int i = 0; i < 9; i++) {
out[i] = bin[i];
}
return out;
}