Write a function called Gray2binary that takes an unsigned character and returns
ID: 3716654 • Letter: W
Question
Write a function called Gray2binary that takes an unsigned character and returns an unsigned character. The returned value is the binary equivalent of the input byte, assuming it was Gray code. To convert from Gray code to binary, compute the bits from left to right as follows: Each bit of the result is an exclusive-OR of that bit position of the original number with the newly computed binary result bit to the left of that bit position. That is, if B_i and G_i are the i-th bits of the binary and Gray code values, respectively, then B_i = G_i ^ B_i+1. Assume a leading zero is in front of the original number, so the MSB (most significant bit) of the result is the same as the MSB of the original. For example, 0b00000000, 0b11000000, 0b00001000, 0b00101010, and 0b01111111 return 0b00000000, 0b10000000, 0b00001111, 0b00110011 and 0b01010101, respectively.
Note: This is for C code.
Explanation / Answer
Please find below program to convert gray to binary
#include<stdio.h>
#include<math.h>
unsigned int GtoB(unsigned int );
int main()
{
unsigned int gray,bin;
printf("enter gray code to be converted:")
scanf("%u",&gray);
bin=GtoB(gray);
printf("converted bin code is: %u",bin);
return 0;
}
unsigned int GtoB(unsigned int n)
{
n = n ^ (n >> 16);
n = n ^ (n >> 8);
n = n ^ (n >> 4);
n = n ^ (n >> 2);
n = n ^ (n >> 1);
return n;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.