-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhw1_binary_hex_converter.c
88 lines (73 loc) · 1.88 KB
/
hw1_binary_hex_converter.c
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
// Fundamental data structure & algorithm
// HW1_02_24_2023
// C language, Encoding = UTF-8
// written by 醫工三 b812109032 許家齊
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
// declare functions
void decimal_to_binary(int num);
void decimal_to_hexadecimal(int num);
void print_binary(int num);
void print_hexadecimal(int num);
// main function
int main(){
// declare variable
int dec;
do{
printf("Please enter an integer between 0 and 255 (enter -1 to exit): ");
if (scanf("%d", &dec) != 1) {
// If the input is not an integer, clear the input buffer
while (getchar() != '\n');
printf("Input error! Please try again.\n");
continue;
}
// exit when input == -1
if (dec == -1) {
break;
}
// assert(dec >= 0 && dec <= 255);
if (dec >= 0 && dec <= 255) {
break;
}
printf("Input error! Please try again.\n");
} while (1);
if (dec == -1) {
printf("Exiting program...\n");
}
else {
printf("The integer you entered is: %d\n", dec);
printf("Decimal = %d\n", dec);
print_binary(dec);
print_hexadecimal(dec);
}
}
void decimal_to_binary(int num) {
if (num > 1) {
decimal_to_binary(num / 2);
}
printf("%d", num % 2);// print remainder
}
void decimal_to_hexadecimal(int num) {
if (num > 15) {
decimal_to_hexadecimal(num / 16);
}
int remainder = num % 16;
if (remainder < 10) {
printf("%d", remainder);
} else {
printf("%c", 'A' + remainder - 10);
}
}
// print binary
void print_binary(int num){
printf("Binary = ");
decimal_to_binary(num);
printf("\n");
}
// print hexadecimal
void print_hexadecimal(int num){
printf("Hexadecimal = ");
decimal_to_hexadecimal(num);
printf("\n");
}