Skip to content

Commit bf74ad3

Browse files
authored
Create bonary_to_gray.c
1 parent e5dad3f commit bf74ad3

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

conversions/bonary_to_gray.c

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
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;

0 commit comments

Comments
 (0)