search
HomeBackend DevelopmentC++Decimal equivalent of Gray code and its reverse order

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

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

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;
}

Output

The decimal equivalent of the gray code of 3 is: 2

Problem Statement 2

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

Example

Input: 15
Output: 10

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

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;
}

Output

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

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
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
C   Interview Questions and Answers: Ace Your Next Technical AssessmentC Interview Questions and Answers: Ace Your Next Technical AssessmentApr 28, 2025 am 12:10 AM

C In interviews, smart pointers are the key tools that help manage memory and reduce memory leaks. 1) std::unique_ptr provides exclusive ownership to ensure that resources are automatically released. 2) std::shared_ptr is used for shared ownership and is suitable for multi-reference scenarios. 3) std::weak_ptr can avoid circular references and ensure secure resource management.

The Future of C  : Adaptations and InnovationsThe Future of C : Adaptations and InnovationsApr 27, 2025 am 12:25 AM

The future of C will focus on parallel computing, security, modularization and AI/machine learning: 1) Parallel computing will be enhanced through features such as coroutines; 2) Security will be improved through stricter type checking and memory management mechanisms; 3) Modulation will simplify code organization and compilation; 4) AI and machine learning will prompt C to adapt to new needs, such as numerical computing and GPU programming support.

The Longevity of C  : Examining Its Current StatusThe Longevity of C : Examining Its Current StatusApr 26, 2025 am 12:02 AM

C is still important in modern programming because of its efficient, flexible and powerful nature. 1)C supports object-oriented programming, suitable for system programming, game development and embedded systems. 2) Polymorphism is the highlight of C, allowing the call to derived class methods through base class pointers or references to enhance the flexibility and scalability of the code.

C# vs. C   Performance: Benchmarking and ConsiderationsC# vs. C Performance: Benchmarking and ConsiderationsApr 25, 2025 am 12:25 AM

The performance differences between C# and C are mainly reflected in execution speed and resource management: 1) C usually performs better in numerical calculations and string operations because it is closer to hardware and has no additional overhead such as garbage collection; 2) C# is more concise in multi-threaded programming, but its performance is slightly inferior to C; 3) Which language to choose should be determined based on project requirements and team technology stack.

C  : Is It Dying or Simply Evolving?C : Is It Dying or Simply Evolving?Apr 24, 2025 am 12:13 AM

C isnotdying;it'sevolving.1)C remainsrelevantduetoitsversatilityandefficiencyinperformance-criticalapplications.2)Thelanguageiscontinuouslyupdated,withC 20introducingfeatureslikemodulesandcoroutinestoimproveusabilityandperformance.3)Despitechallen

C   in the Modern World: Applications and IndustriesC in the Modern World: Applications and IndustriesApr 23, 2025 am 12:10 AM

C is widely used and important in the modern world. 1) In game development, C is widely used for its high performance and polymorphism, such as UnrealEngine and Unity. 2) In financial trading systems, C's low latency and high throughput make it the first choice, suitable for high-frequency trading and real-time data analysis.

C   XML Libraries: Comparing and Contrasting OptionsC XML Libraries: Comparing and Contrasting OptionsApr 22, 2025 am 12:05 AM

There are four commonly used XML libraries in C: TinyXML-2, PugiXML, Xerces-C, and RapidXML. 1.TinyXML-2 is suitable for environments with limited resources, lightweight but limited functions. 2. PugiXML is fast and supports XPath query, suitable for complex XML structures. 3.Xerces-C is powerful, supports DOM and SAX resolution, and is suitable for complex processing. 4. RapidXML focuses on performance and parses extremely fast, but does not support XPath queries.

C   and XML: Exploring the Relationship and SupportC and XML: Exploring the Relationship and SupportApr 21, 2025 am 12:02 AM

C interacts with XML through third-party libraries (such as TinyXML, Pugixml, Xerces-C). 1) Use the library to parse XML files and convert them into C-processable data structures. 2) When generating XML, convert the C data structure to XML format. 3) In practical applications, XML is often used for configuration files and data exchange to improve development efficiency.

See all articles

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

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function