- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Program to Convert Binary to Gray Code
When it is required to convert binary code to gray code, a method is defined that performs the ‘xor’ operation.
Below is the demonstration of the same −
Example
def binary_to_gray_op(n): n = int(n, 2) n ^= (n >> 1) return bin(n)[2:] gray_val = input('Enter the binary number: ') binary_val = binary_to_gray_op(gray_val) print('Gray codeword is :', binary_val)
Output
Enter the binary number: 101100110 Gray codeword is : 111010101
Explanation
A method named ‘binary_to_gray_op’ is defined, that takes the binary number as its parameter.
It performs the ‘xor’ operation.
It returns the converted output.
The input of binary number is taken from the user.
The function is called, and this value is passed as a parameter to it.
The converted output is displayed on the console.
Advertisements