-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbcd_add.c
More file actions
105 lines (78 loc) · 2.23 KB
/
bcd_add.c
File metadata and controls
105 lines (78 loc) · 2.23 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
WeChat: cstutorcs
QQ: 749389476
Email: tutorcs@163.com
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <ctype.h>
#include <string.h>
//
// Store an arbitray length Binary Coded Decimal number.
// bcd points to an array of size n_bcd
// Each array element contains 1 decimal digit.
// Digits are stored in reverse order.
//
// For example if 42 is stored then
// n_bcd == 2
// bcd[0] == 0x02
// bcd[1] == 0x04
//
typedef struct big_bcd {
unsigned char *bcd;
int n_bcd;
} big_bcd_t;
big_bcd_t *bcd_add(big_bcd_t *x, big_bcd_t *y);
void bcd_print(big_bcd_t *number);
void bcd_free(big_bcd_t *number);
big_bcd_t *bcd_from_string(char *string);
int main(int argc, char *argv[]) {
if (argc != 3) {
fprintf(stderr, "Usage: %s <number> <number>\n", argv[0]);
exit(1);
}
big_bcd_t *left = bcd_from_string(argv[1]);
big_bcd_t *right = bcd_from_string(argv[2]);
big_bcd_t *result = bcd_add(left, right);
bcd_print(result);
printf("\n");
bcd_free(left);
bcd_free(right);
bcd_free(result);
return 0;
}
// DO NOT CHANGE THE CODE ABOVE HERE
big_bcd_t *bcd_add(big_bcd_t *x, big_bcd_t *y) {
// PUT YOUR CODE HERE
}
// DO NOT CHANGE THE CODE BELOW HERE
// print a big_bcd_t number
void bcd_print(big_bcd_t *number) {
// if you get an error here your bcd_add is returning an invalid big_bcd_t
assert(number->n_bcd > 0);
for (int i = number->n_bcd - 1; i >= 0; i--) {
putchar(number->bcd[i] + '0');
}
}
// free storage for big_bcd_t number
void bcd_free(big_bcd_t *number) {
// if you get an error here your bcd_add is returning an invalid big_bcd_t
// or it is calling free for the numbers it is given
free(number->bcd);
free(number);
}
// convert a string to a big_bcd_t number
big_bcd_t *bcd_from_string(char *string) {
big_bcd_t *number = malloc(sizeof *number);
assert(number);
int n_digits = strlen(string);
assert(n_digits);
number->n_bcd = n_digits;
number->bcd = malloc(n_digits * sizeof number->bcd[0]);
assert(number->bcd);
for (int i = 0; i < n_digits; i++) {
int digit = string[n_digits - i - 1];
assert(isdigit(digit));
number->bcd[i] = digit - '0';
}
return number;
}