# Gray Code to Binary Code Conversion!

Page 1 of 1

## 1 Replies - 11722 Views - Last Post: 14 March 2011 - 08:26 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'https://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=222116&amp;s=586e0a360fae7c60d3242df2b7518fee&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 Reality-Check

Reputation: 0
• Posts: 1
• Joined: 14-March 11

# Gray Code to Binary Code Conversion!

Posted 14 March 2011 - 04:12 PM

Hi guys,

So I'm trying to write a function that will convert a 7-bit Gray code to the corresponding 7-bit Binary Code.

Here's how to convert -

* Gray Value bits ---- MS bit > G6 G5 G4 G3 G2 G1 G0
*
* Binary Value bits -- MS bit > B6 B5 B4 B3 B2 B1 B0
*

* B6 = G6 // MS bits always the same
* B5 = B6 ^ G5 // Exclusive 'OR' the bits together to construct the 7 bit binary value
* B4 = B5 ^ G4
* B3 = B4 ^ G3
* B2 = B3 ^ G2
* B1 = B2 ^ G1
* B0 = B1 ^ G0

and here's my function so far-

```
unsigned short Gray_to_Bin(unsigned short Gray)
{
unsigned short Bin;
unsigned short i;

Bin = 0;

Gray &= 0x7f;           // Mask bit 7 (Index Bit)
Bin = Gray & mask;         // Set B6 = G6

for (i=0; i<6; i++)        // Set B5, B4, ..., B0
{

// Code needed here!!

}
return Bin;
}

```

----------------------

I need to find a way to access the specific bits required for each run of the loop, but I'm unsure of how to do this...

Any ideas/pointers? Thanks

Is This A Good Question/Topic? 0

## Replies To: Gray Code to Binary Code Conversion!

### #2 KiddKoder

Reputation: 1
• Posts: 42
• Joined: 30-October 10

## Re: Gray Code to Binary Code Conversion!

Posted 14 March 2011 - 08:26 PM

To my understanding it would work better if it was an array of bits... say B[6], B[5],... and so on.

Then in the loop you could say B[i] = B[i + 1] ^ G[i]

I'm not sure if it would work or not, but that is my best guess.

This post has been edited by KiddKoder: 14 March 2011 - 08:27 PM