Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR C

generate n-bit gray code in c

#include <stdio.h>
#include <math.h>
int decimal_to_binary(int);
int main(void)
{
    int bits,gray;
    printf("What is the number of bits? ");
    scanf("%d",&bits);
    int max_num = pow(2,bits)-1;
    for(int j=0; j<=max_num; j++)
    {
        gray=j^(j>>1);
        printf("%d
",decimal_to_binary(gray));
    }
    return 0;
}
int decimal_to_binary(int num)
{
    int binary=0,i=0;
    while(num!=0)
    {
        int reminder = num%2;
        binary += reminder*pow(10,i);
        num/=2;
        i++;
    }
    return binary;
}
 
PREVIOUS NEXT
Tagged: #generate #gray #code
ADD COMMENT
Topic
Name
4+9 =