Table of Contents
prerequisites
Problem Statement 2
Example
solution
Binary to Gray code conversion
Algorithm: Using bitwise operators
Output
Conversion from Gray code to binary code
in conclusion
Home Backend Development C++ Decimal equivalent of Gray code and its reverse order

Decimal equivalent of Gray code and its reverse order

Sep 07, 2023 pm 06:33 PM
gray code decimal equivalent

Decimal equivalent of Gray code and its reverse order

Gray code or reflected binary code is a binary representation of a number in which two consecutive numbers differ by only one bit.

For example, the Gray code of 1 is 001, and the Gray code of 2 is 011.

Gray code is often used for error correction because it prevents some data errors that can occur in the usual binary representation when state changes.

Due to its unique properties, Gray code is also helpful in k-map, communication, etc.

prerequisites

Before reading further, please study decimal, binary and Gray code notation.

Problem Statement 1

Given a decimal number n, find the Gray code of the decimal form of the number.

Example

Input: 3
Output: 2
Copy after login

Explanation -> The binary representation of 3 is 011. Its Gray code representation is 010. The decimal representation of 010 is 2.

Thus, the Gray code decimal equivalent of 3 is 2.

Input: 5
Output: 7
Copy after login

Explanation -> The binary representation of 5 is 101. Its Gray code representation is 111 and its decimal representation is 7.

Thus, the Gray code decimal equivalent of 5 is 7.

solution

The compiler understands numbers in binary format.

So, in our program, when we enter a number in decimal format, it is interpreted as binary.

So we just need to convert the number from its binary equivalent to its Gray code.

Binary to Gray code conversion

The binary representation is equal to the leftmost bit of the Gray code. The following bits on the right side are found by XORing consecutive binary bits.

For example -

Consider n = 3. The binary code for 3 is 011.

  • The leftmost bits of binary code and Gray code are equal. Therefore, the first bit from the left in Gray code is 0.

  • For the second digit from the left, XOR the first and second digits from the left in the binary code. 0 XOR 1 = 1.

  • For the third digit from the left, XOR the second and third digits from the left in the binary code. 1 XOR 1 = 0.

So Gray code: 010.

Algorithm: Using bitwise operators

We can obtain the Gray code of number n through the following steps -

  • n Shift right by 1.

  • XOR the right-shifted number with the original n.

Example

The following is a C program that uses bitwise operators to find Gray code from binary code

#include <bits/stdc++.h>
using namespace std;
//This function returns the decimal equivalent
// of the gray code of n.
int dec_equi_of_gray(int n) {
   return n ^ (n >> 1);
}
int main(){
   int n = 3;
   cout<<"The decimal equivalent of the gray code of 3 is: ";
   
   //Function call to convert binary code to gray code
   cout << dec_equi_of_gray(n) << endl;
   return 0;
}
Copy after login

Output

The decimal equivalent of the gray code of 3 is: 2
Copy after login

Problem Statement 2

Given the decimal value of Gray code, find its decimal code value.

Example

Input: 15
Output: 10
Copy after login

Explanation -> Gray code given as input: 1111 (binary value 15).

Now, convert the Gray code to binary code to get 1010 from 1111.

1010 is the binary value of 10. Hence the output.

Input: 10
Output: 12
Copy after login

Explanation -> Gray code given as input: 1010 (binary value 10).

The binary system of Gray code 1010 is 1100. The decimal system of 1100 is 12.

Conversion from Gray code to binary code

The leftmost bit (MSB) of the binary code is the same as the MSB of the Gray code. The following bits are found by XORing the previous indexed binary bit with the current indexed grayscale bit.

Example: Consider Gray code 1111.

  • The MSB of the binary code will be the same as the MSB of the Gray code. Therefore, the MSB will be 1.

  • For the left two bits, check the XOR of the left two bits of the Gray code and the leftmost bit of the binary code. Therefore, 1^1 = 0.

  • Similarly, for the third leftmost digit, 0 ^ 1 = 1.

  • For the fourth leftmost digit, 1 ^ 1 = 0.

So binary code: 1010.

Example

Below is a C program to find binary code from Gray code using bitwise operators

#include <bits/stdc++.h>
using namespace std;

//This function returns the decimal value of 
//the binary code converted from the gray code n.
int gray_to_binary(int n){
   int binary = n;
   while (n > 0){
      n >>= 1;
      binary ^= n;
   }
   return binary;
}
// Driver Code
int main(){
   int n = 15;
   cout<<"The decimal value of the binary code converted from the gray code is: ";
   
   // Function call to convert gray code to binary code
   cout << gray_to_binary(n) << endl;
   
   return 0;
}
Copy after login

Output

The decimal value of the binary code converted from the gray code is: 10
Copy after login

in conclusion

This article solves the problem of finding the Gray code decimal equivalent and its inverse of a given number n. We solved this problem using bitwise operators. C programs are provided for both parts of the problem.

The above is the detailed content of Decimal equivalent of Gray code and its reverse order. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

C language data structure: data representation and operation of trees and graphs C language data structure: data representation and operation of trees and graphs Apr 04, 2025 am 11:18 AM

C language data structure: The data representation of the tree and graph is a hierarchical data structure consisting of nodes. Each node contains a data element and a pointer to its child nodes. The binary tree is a special type of tree. Each node has at most two child nodes. The data represents structTreeNode{intdata;structTreeNode*left;structTreeNode*right;}; Operation creates a tree traversal tree (predecision, in-order, and later order) search tree insertion node deletes node graph is a collection of data structures, where elements are vertices, and they can be connected together through edges with right or unrighted data representing neighbors.

The truth behind the C language file operation problem The truth behind the C language file operation problem Apr 04, 2025 am 11:24 AM

The truth about file operation problems: file opening failed: insufficient permissions, wrong paths, and file occupied. Data writing failed: the buffer is full, the file is not writable, and the disk space is insufficient. Other FAQs: slow file traversal, incorrect text file encoding, and binary file reading errors.

How to calculate c-subscript 3 subscript 5 c-subscript 3 subscript 5 algorithm tutorial How to calculate c-subscript 3 subscript 5 c-subscript 3 subscript 5 algorithm tutorial Apr 03, 2025 pm 10:33 PM

The calculation of C35 is essentially combinatorial mathematics, representing the number of combinations selected from 3 of 5 elements. The calculation formula is C53 = 5! / (3! * 2!), which can be directly calculated by loops to improve efficiency and avoid overflow. In addition, understanding the nature of combinations and mastering efficient calculation methods is crucial to solving many problems in the fields of probability statistics, cryptography, algorithm design, etc.

What are the basic requirements for c language functions What are the basic requirements for c language functions Apr 03, 2025 pm 10:06 PM

C language functions are the basis for code modularization and program building. They consist of declarations (function headers) and definitions (function bodies). C language uses values ​​to pass parameters by default, but external variables can also be modified using address pass. Functions can have or have no return value, and the return value type must be consistent with the declaration. Function naming should be clear and easy to understand, using camel or underscore nomenclature. Follow the single responsibility principle and keep the function simplicity to improve maintainability and readability.

Function name definition in c language Function name definition in c language Apr 03, 2025 pm 10:03 PM

The C language function name definition includes: return value type, function name, parameter list and function body. Function names should be clear, concise and unified in style to avoid conflicts with keywords. Function names have scopes and can be used after declaration. Function pointers allow functions to be passed or assigned as arguments. Common errors include naming conflicts, mismatch of parameter types, and undeclared functions. Performance optimization focuses on function design and implementation, while clear and easy-to-read code is crucial.

C language multithreaded programming: a beginner's guide and troubleshooting C language multithreaded programming: a beginner's guide and troubleshooting Apr 04, 2025 am 10:15 AM

C language multithreading programming guide: Creating threads: Use the pthread_create() function to specify thread ID, properties, and thread functions. Thread synchronization: Prevent data competition through mutexes, semaphores, and conditional variables. Practical case: Use multi-threading to calculate the Fibonacci number, assign tasks to multiple threads and synchronize the results. Troubleshooting: Solve problems such as program crashes, thread stop responses, and performance bottlenecks.

Concept of c language function Concept of c language function Apr 03, 2025 pm 10:09 PM

C language functions are reusable code blocks. They receive input, perform operations, and return results, which modularly improves reusability and reduces complexity. The internal mechanism of the function includes parameter passing, function execution, and return values. The entire process involves optimization such as function inline. A good function is written following the principle of single responsibility, small number of parameters, naming specifications, and error handling. Pointers combined with functions can achieve more powerful functions, such as modifying external variable values. Function pointers pass functions as parameters or store addresses, and are used to implement dynamic calls to functions. Understanding function features and techniques is the key to writing efficient, maintainable, and easy to understand C programs.

How to output a countdown in C language How to output a countdown in C language Apr 04, 2025 am 08:54 AM

How to output a countdown in C? Answer: Use loop statements. Steps: 1. Define the variable n and store the countdown number to output; 2. Use the while loop to continuously print n until n is less than 1; 3. In the loop body, print out the value of n; 4. At the end of the loop, subtract n by 1 to output the next smaller reciprocal.

See all articles