Convert Gray-Code to decimal/binary and back
Gray-Code is a binary code developed by Frank Gray in 1947. It is used by most absolute incremental encoders and some favor it's use for fringe projection systems that have to encode the pixel data in a series of image patterns (mostly fringes with differing widths). To convert Gray-Code from and to Decimal numbers using c++ i had to look up different approaches with varying difficulty levels. I then compiled the following algorithms, that i will be using for my own fringe projection system (keep tuned).
It's rather easy if you know how to do it. I had to find out the hard way, so here's for the rest of the world:
First the easy part: transforming a integer number dec into a Gray-code _code:
-
void _calculateGrayCode () {
-
bitset<numeric_limits<int>::digits + 1> bs(dec);
-
bitset<numeric_limits<int>::digits + 1> gs(dec);
-
bitset<numeric_limits<int>::digits + 1> _code(0);
-
bs>>= 1;
-
gs ^= bs;
-
for (unsigned i=0; i<_code.size(); i++){
-
_code[i] = gs[i];
-
gs[i]=0;
-
}
-
}
Now to the part of converting Gray-Code to binary and then decimal number: Suppose our Gray-code is inside the bitset _code.
-
void _calculateNumber () {
-
bitset<numeric_limits<int>::digits + 1> gs(0);
-
bitset<numeric_limits<int>::digits + 1> bs(0);
-
for (unsigned i=0; i<_code.size(); i++){
-
gs[i] = _code[i];
-
}
-
bs[gs.size()-1] = gs[gs.size()-1];
-
for (int i=gs.size()-2; i>=0;i--){
-
bs[i]=bs[i+1];
-
bs[i]=bs[i]^gs[i];
-
}
-
_number = static_cast<int>(bs.to_ulong());
-
}
bs holds the binary representation of the Gray-Code and _number is the decimal respresentation.
References:
- Gray code algorithms in Ruby by Wayne Conrad
- Gray-Code implementation in Java