Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Binary to Gray code using recursion in C program
A Binary number is a number that has only two bits 0 and 1. Gray code is a special type of binary number that has a property that two successive numbers of the code cannot differ by more than one bit. This property of gray code makes it useful in K-maps, error correction, communication, etc.
This makes the conversion of binary to gray code necessary. So, let's see an algorithm to convert binary to gray code using recursion.
Syntax
int binaryToGray(int binary);
Algorithm
Step 1: For input n:
Step 1.1: if n = 0, return 0
Step 1.2: if the last two bits are opposite,
gray = 1 + 10*(recursive call with n/10)
Step 1.3: if the last two bits are same,
gray = 10*(recursive call with n/10)
Step 2: Print gray code
Step 3: EXIT
Example
Let's take an example of binary to gray code conversion −
#include <stdio.h>
int binaryToGray(int n) {
if (n == 0)
return 0;
int lastBit = n % 10;
int secondLastBit = (n / 10) % 10;
/* If last two bits are different (XOR operation) */
if ((lastBit && !secondLastBit) || (!lastBit && secondLastBit))
return (1 + 10 * binaryToGray(n / 10));
/* If last two bits are same */
return (10 * binaryToGray(n / 10));
}
int main() {
int binaryNumber = 1001;
printf("Binary number: %d
", binaryNumber);
printf("Gray code: %d
", binaryToGray(binaryNumber));
/* Another example */
binaryNumber = 100110001;
printf("\nBinary number: %d
", binaryNumber);
printf("Gray code: %d
", binaryToGray(binaryNumber));
return 0;
}
Binary number: 1001 Gray code: 1101 Binary number: 100110001 Gray code: 110101001
How It Works
The recursive function works by comparing adjacent bits from right to left. The most significant bit of gray code is always the same as the most significant bit of binary. For remaining bits, if two adjacent bits in binary are different, the corresponding gray code bit is 1, otherwise it's 0.
Key Points
- The first bit of gray code is always same as the first bit of binary number.
- For other bits, we perform XOR operation between adjacent bits of binary number.
- The recursion processes bits from right to left, building the result from least significant to most significant bit.
Conclusion
Binary to gray code conversion using recursion provides an elegant solution by processing adjacent bits. The recursive approach naturally handles the bit-by-bit comparison required for gray code generation.
