Convert Gray code to binary using bitset in C++

Updated

Given N in Gray code equivalent. Find its binary equivalent and return decimal form using bitset in O(1)

Examples :

Input 4: 
Output 7:

Input 15:
Output 10:

We are using bitset class of C++ for handling bits of the number.We are traversing number from left and taking xor of previous bit of the result with current bit.

Note : MSB of number is copied directly into result

Implementation :

#include<bits/stdc++.h>
using namespace std;
int grayToBinary(int n)
{
    
    bitset<32>b;
    bitset<32>c;

    //converting number into bitset
    b|=n;

    //iterating through all bit of the numbers
    for(int i=31;i>=0;i--)
    {
        c[i]=b[i]^(i==31?0:c[i+1]);
    }
    return (int)c.to_ulong();
}
int main()
{
  cout<<grayToBinary(4)<<"\n"; cout<<grayToBinary(15)<<"\n"; return 0;
} 
Comment
Next tutorial
Mithlesh Upadhyay Published 1 Dec 2026 · 1 min read

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.

Related tutorials