VOOZH about

URL: https://www.geeksforgeeks.org/dsa/gray-to-binary-and-binary-to-gray-conversion/

⇱ Gray to Binary and Binary to Gray conversion - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Gray to Binary and Binary to Gray conversion

Last Updated : 3 Oct, 2025

Given a number n, convert it from binary to Gray code and also convert n into Gray code to binary.

Input : n = 5
Output: Binary to Gray : 7
Gray to Binary : 6
Explanation: Binary to Gray gives 7 (binary 101 → gray 111), and gray to binary converts gray code 5 (binary 101) to binary 6 (110)

Binary to Gray conversion :

  1. The Most Significant Bit (MSB) of the gray code is always equal to the MSB of the given binary code.
  2. Other bits of the output gray code can be obtained by XORing binary code bit at that index and previous index.
👁 Image
Binary code to gray code conversion

Gray to binary conversion :

  1. The Most Significant Bit (MSB) of the binary code is always equal to the MSB of the given gray code.
  2. Other bits of the output binary code can be obtained by checking the gray code bit at that index. If the current gray code bit is 0, then copy the previous binary code bit, else copy the invert of the previous binary code bit.
👁 Image
Gray code to binary code conversion

When n is given in binary


Output
Binary to Gray: 01101
Gray to Binary: 01001

Time Complexity: O(n), where n is length of the binary string.
Auxiliary Space: O(n)

When n is given in interger


Output
Binary to Gray: 7
Gray to Binary: 6

Time Complexity:

  • For binary to gray conversion: O(1)
  • For gray to binary conversion: O(log(n)), as n is a decimal number and number of bits is approximately log(n).

Auxiliary Space: O(1)

Related Article:

Generate n-bit Gray Codes

Comment