File tree Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Original file line number Diff line number Diff line change 1+ #include <stdio.h>
2+ #include <math.h>
3+
4+ // Function to convert binary to decimal
5+ int binaryToDecimal (long long binary ) {
6+ int decimal = 0 , i = 0 , remainder ;
7+ while (binary != 0 ) {
8+ remainder = binary % 10 ;
9+ binary /= 10 ;
10+ decimal += remainder * pow (2 , i );
11+ ++ i ;
12+ }
13+ return decimal ;
14+ }
15+
16+ // Function to convert decimal to binary
17+ long long decimalToBinary (int decimal ) {
18+ long long binary = 0 ;
19+ int remainder , i = 1 ;
20+
21+ while (decimal != 0 ) {
22+ remainder = decimal % 2 ;
23+ decimal /= 2 ;
24+ binary += remainder * i ;
25+ i *= 10 ;
26+ }
27+ return binary ;
28+ }
29+
30+ // Function to convert binary to Gray code
31+ long long binaryToGray (long long binary ) {
32+ // Convert binary to decimal first
33+ int decimal = binaryToDecimal (binary );
34+
35+ // Perform XOR between decimal and decimal right-shifted by 1
36+ int grayDecimal = decimal ^ (decimal >> 1 );
37+
38+ // Convert Gray code back to binary representation for display
39+ return decimalToBinary (grayDecimal );
40+ }
41+
42+ int main () {
43+ long long binary ;
44+
45+ printf ("Enter a binary number: " );
46+ scanf ("%lld" , & binary );
47+
48+ // Validate input
49+ long long temp = binary ;
50+ while (temp > 0 ) {
51+ if (temp % 10 > 1 ) {
52+ printf ("❌ Invalid input! Please enter only 0s and 1s.\n" );
53+ return 0 ;
54+ }
55+ temp /= 10 ;
You can’t perform that action at this time.
0 commit comments