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 number of the code cannot differ more than one bit. This property of gray code makes it useful more 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.
Example
Let’s take an example of gray code co
Input : 1001 Output : 1101
Algorithm
Step 1 : Do with input n : Step 1.1 : if n = 0, gray = 0 ; Step 1.2 : if the last two bits are opposite, gray = 1 + 10*(go to step 1 passing n/10). Step 1.3 : if the last two bits are same, gray = 10*(go to step 1 passing n/10). Step 2 : Print gray. Step 3 : EXIT.
Example
#include <iostream> using namespace std; int binaryGrayConversion(int n) { if (!n) return 0; int a = n % 10; int b = (n / 10) % 10; if ((a && !b) || (!a && b)) return (1 + 10 * binaryGrayConversion(n / 10)); return (10 * binaryGrayConversion(n / 10)); } int main() { int binary_number = 100110001; cout<<"The binary number is "<<binary_number<<endl; cout<<"The gray code conversion is "<<binaryGrayConversion(binary_number); return 0; }
Output
The binary number is 100110001 The gray code conversion is 110101001