Binary numbers are numbers with only two digits, 0 and 1.
Gray code is a special type of binary number whose property is that two consecutive digits of the code em> cannot differ by more than one digit. This property of Gray code makes it more useful in K-map, error correction, communication, etc.
This makes binary to Gray code conversion necessary. So, let us look at the algorithm to convert binary to Gray code Use recursion.
Let us take Gray code code as an example
Input : 1001 Output : 1101
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.
#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; }
The binary number is 100110001 The gray code conversion is 110101001
The above is the detailed content of Translate the following into Chinese: Convert binary to gray code in C program using recursion. For more information, please follow other related articles on the PHP Chinese website!