@@ -6,11 +6,88 @@ Input a binary number :1001
6
6
Expected Output :
7
7
The Binary Number : 1001
8
8
The equivalent Octal Number : 11
9
+
10
+ + 1. Figure out how to convert binary straight to octal
11
+ At this moment I can binary -> decimal -> octal. There probably is a better way to do this:
12
+ Convert every 3 binary digits (start from bit 0) to 1 octal digit, with binary table from 0 to 7
13
+ Ex: 00001100010001 = 00 001 100 010 001 = 1 4 2 1 = 1421
14
+ 2. Input a dinamic array of chars
15
+ 3. Convertion:
16
+ Enum of binary valies from 0 to 7
17
+ Iterate over an array, assign each pair of three from the end of the array octal value
18
+ Output the value
19
+ 4. Invalid input
20
+ 5. Test
21
+ 6. Cpplint test
22
+ 7. Add and push
9
23
*/
10
24
11
25
#include <stdio.h>
26
+ #include <stdlib.h>
12
27
13
- int main () {
28
+ enum is_valid {
29
+ TRUE = 1 ,
30
+ FALSE = 0
31
+ };
32
+
33
+ int input_binary (char * pointer_to_binary_array );
34
+ void print_invalid_input ();
35
+ void print_binary_array (char * pointer_to_binary_array );
14
36
37
+ int main () {
38
+ char * pointer ;
39
+ pointer = (char * )malloc (1 * sizeof (char ));
40
+ if (pointer == NULL ) {
41
+ printf ("Memory could not be allocated" );
42
+ } else {
43
+ int is_valid = input_binary (pointer );
44
+ print_binary_array (pointer );
45
+ if (is_valid == FALSE) {
46
+ print_invalid_input ();
47
+ }
48
+ }
15
49
return 0 ;
16
50
}
51
+
52
+ void print_binary_array (char * pointer_to_binary_array ) {
53
+ for (int i = 0 ; ;++ i ) {
54
+ if (pointer_to_binary_array [i ] == '\0' ) {
55
+ break ;
56
+ }
57
+ printf ("%c" , pointer_to_binary_array [i ]);
58
+ }
59
+ }
60
+
61
+ void print_invalid_input () {
62
+ printf ("n/a" );
63
+ }
64
+
65
+ int input_binary (char * pointer_to_binary_array ) {
66
+ int array_lenght = 1 , is_valid = TRUE;
67
+ char endline = '\n' , temp_char = '\0' ;
68
+ for (int i = 0 ; i < array_lenght ; ++ i ) {
69
+ if (!scanf ("%c" , & temp_char )) {
70
+ if (pointer_to_binary_array ) {
71
+ free (pointer_to_binary_array );
72
+ pointer_to_binary_array = NULL ;
73
+ }
74
+ is_valid = FALSE;
75
+ } else {
76
+ if (temp_char == endline ) {
77
+ pointer_to_binary_array [i ] = '\0' ;
78
+ break ;
79
+ }
80
+ if (temp_char != '1' && temp_char != '0' ) {
81
+ is_valid = FALSE;
82
+ if (pointer_to_binary_array ) {
83
+ free (pointer_to_binary_array );
84
+ pointer_to_binary_array = NULL ;
85
+ }
86
+ }
87
+ pointer_to_binary_array [i ] = temp_char ;
88
+ ++ array_lenght ;
89
+ pointer_to_binary_array = (char * )realloc (pointer_to_binary_array , (array_lenght )* sizeof (char ));
90
+ }
91
+ }
92
+ return is_valid ;
93
+ }
0 commit comments