1
+ #include <stdio.h>
2
+ #include <stdlib.h>
3
+ #include <math.h>
4
+
5
+ int revDigits (int n , int zeros )
6
+ {
7
+ int rev = 0 ;
8
+
9
+ while (n > 0 ){
10
+ rev = rev * 10 + n % 10 ;
11
+ n = n /10 ;
12
+ }
13
+ rev = rev * pow (10 , zeros );
14
+ return rev ;
15
+ }
16
+
17
+ int count (int bin )
18
+ {
19
+ int nDigits = floor (log10 (abs (bin ))) + 1 ;
20
+ return nDigits ;
21
+ }
22
+
23
+ char * revChars (char * hex , int length )
24
+ {
25
+ int i = length - 1 , j = 0 ;
26
+ char * rev = (char * )malloc (length + 1 * sizeof (char ));
27
+
28
+ while (i >= 0 ){
29
+ rev [j ] = hex [i ];
30
+ j ++ ; i -- ;
31
+ }
32
+
33
+ rev [j ] = '\0' ;
34
+ return rev ;
35
+ }
36
+
37
+ int decimalToBinary (int number )
38
+ {
39
+
40
+ int bin = 0 ;
41
+ int totLength = 0 ;
42
+ while (number > 0 ){
43
+ bin = bin * 10 + number % 2 ;
44
+ number = number /2 ;
45
+ totLength ++ ;
46
+ }
47
+ int zeros = totLength - count (bin );
48
+
49
+ return revDigits (bin , zeros );
50
+ }
51
+
52
+ int decimalToOctal (int number )
53
+ {
54
+ int oct = 0 ;
55
+ int totLength = 0 ;
56
+
57
+ while (number > 0 ){
58
+ oct = oct * 10 + number % 8 ;
59
+ number = number / 8 ;
60
+ totLength ++ ;
61
+ }
62
+ int zeros = totLength - count (oct );
63
+
64
+ return revDigits (oct , zeros );
65
+ }
66
+
67
+ char * decimalToHexa (int number )
68
+ {
69
+ int i = 0 , j ;
70
+
71
+ char * hex = (char * )malloc (80 * sizeof (char ));
72
+ char hexcodes [6 ][2 ] = {"A" , "B" , "C" , "D" , "E" , "F" };
73
+
74
+ while (number > 0 ){
75
+
76
+ if (number %16 > 9 )
77
+ {
78
+ hex [i ] = hexcodes [(number %16 )%10 ][0 ];
79
+ }
80
+ else
81
+ {
82
+ hex [i ] = (number % 16 ) + 48 ;
83
+ }
84
+
85
+ number = number / 16 ;
86
+ i ++ ;
87
+ }
88
+ hex [i ] = '\0' ;
89
+ return revChars (hex , i );
90
+ }
91
+
92
+ int main ()
93
+ {
94
+ int i , number , pos , bin , oct ;
95
+ char * hex ;
96
+ printf ("Enter the number" );
97
+ scanf ("%d" , & number );
98
+
99
+ // printf("Enter the position to set bit");
100
+ // scanf("%d",&pos);
101
+
102
+ bin = decimalToBinary (number );
103
+ oct = decimalToOctal (number );
104
+ hex = decimalToHexa (number );
105
+
106
+ printf ("Binary :%d\n" , bin );
107
+ printf ("Octal :%d\n" , oct );
108
+ printf ("Hexadecimal :%s" , hex );
109
+
110
+ return 0 ;
111
+ }
0 commit comments