File tree Expand file tree Collapse file tree 1 file changed +25
-0
lines changed
Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Original file line number Diff line number Diff line change 1+ # Function to convert Binary number to Gray code
2+ def binary_to_gray (binary ):
3+ # Convert binary (string) to integer
4+ binary = int (binary , 2 )
5+
6+ # Perform XOR between binary and binary right-shifted by 1 bit
7+ gray = binary ^ (binary >> 1 )
8+
9+ # Convert back to binary string and remove '0b' prefix
10+ gray_code = bin (gray )[2 :]
11+
12+ return gray_code
13+
14+
15+ # --- Main Program ---
16+
17+ # Taking input from the user
18+ binary_input = input ("Enter a binary number: " )
19+
20+ # Input validation
21+ if not all (bit in '01' for bit in binary_input ):
22+ print ("❌ Invalid input! Please enter a binary number (0s and 1s only)." )
23+ else :
24+ gray_result = binary_to_gray (binary_input )
25+ print (f"✅ The Gray code for binary { binary_input } is: { gray_result } " )
You can’t perform that action at this time.
0 commit comments