1.11M Members

This will convert a decimal number into Gray code .

``````/////////////////////////////////////////////////////////////
////     Coverting a decimal number to Gray code       /////
///////////////////////////////////////////////////////////

# include<stdio.h>
# include<conio.h>
# include<stdlib.h>
static int a[8],b[8],k=1,i;
void main()
{   int n1;
clrscr();
printf("Enter any Numbers :");
scanf("%d",&n1);
while(n1!=0)   /* converting number to its binary equivalent */
{  a[i]=n1 % 2;
n1/=2;
i++;
}
/* printing binary equivalent */
printf("\nThe binary code of the given number is :");
for(i=7;i>=0;i--)
printf("%d",a[i]);

/* gray code conversion */
b[0]=a[7];

for(i=7;i>=0;i--)
{  if(a[i]==0 && a[i-1]==0)
b[k]=0;
if(a[i]==1 && a[i-1]==1)
b[k]=0;
if(a[i]==0 && a[i-1]==1)
b[k]=1;
if(a[i]==1 && a[i-1]==0)
b[k]=1;
k++;
}

/* printing the gray code */
printf("\nThe gray code of the given number is :");
for(i=0;i<8;i++)
printf("%d",b[i]);
}
``````

What is grey code?

``````#include<stdio.h>
#include<conio.h>
void main()
{int a[10],i=0,c=0,n,b[10];
printf("\n enter the binary code");
scanf("%d",&n);
while(n!=0)
{a[i]=n%10;
n/=10;
i++;
c++;
}
for(i=c-1;i>=0;i--)
{
b[i]=a[i];
}
for(i=c-1;i>=0;i--)
{
if(b[i]==1)
{
if(a[i-1]==1)
a[i-1]=0;
else
a[i-1]=1;
}
}
printf("\n the gray code is");
for(i=c-1;i>=0;i--)
printf("%d",a[i]);
getch();
}``````

Here is a more refined version that only requires one array, can be up to 32bit and includes a proving decode that's useful in its own right for rotary encoders.

``````/*
Convert decimal number to Grey code and back again
*/

# include<stdio.h>

#define SIZE 32

int bits[SIZE], i; // could be chars in 8 bit machine
unsigned long num; // could be int if less than 17 bit Grey code

void main(){
printf("\n    ");
printf("%d",SIZE);
printf(" bit number conversion\n");

printf("\n Enter number     ");
scanf("%lu",&num);

/* converting number to binary equivalent */
/* MSB is 1st element in array */
for(i = 0; i < SIZE; i ++){
bits[SIZE-1-i] = (num >> i) & 1;
}

/* printing binary */
printf(" Binary           ");
for(i = 0; i < SIZE; i ++){
printf("%d",bits[i]);
}

/* in-line gray code conversion */
for(i = SIZE-1; i > 0; i --){
bits[i] = bits[i] ^ bits[i - 1];
}

/* printing gray code */
printf("\n Gray code        ");
for(i = 0; i < SIZE; i ++){
printf("%d",bits[i]);
}

/* in-line conversion back to binary */
for(i = 1; i < SIZE; i++){
bits[i] = bits[i] ^ bits[i - 1];
}

/* reprinting binary */
printf("\n Restored binary  ");
for(i=0;i<SIZE;i++){
printf("%d",bits[i]);
}

/* convert back to decimal */
num = 0;
for (i = 0; i < SIZE; i ++){
num = (num<<1) | bits[i];
}

/* reprinting decimal number */
printf("\n Restored decimal ");
printf("%lu",num);
printf("\n");
}``````

x^(x>>1)

You
Post:
View similar articles that have also been tagged: