Im working for a python project and i wonder if the following is possible:
Currently I have a graycode stored as an string i.e: "1000" and I want to convert it to is integer (decimal, base10) value --> 15
CodePudding user response:
From RosettaCode:
def gray_decode(n):
m = n >> 1
while m:
n ^= m
m >>= 1
return n
This takes an int
as input, so you would have to parse the string before calling the function:
a = "1000"
print(gray_decode(int(a, 2)))
CodePudding user response:
there is a good example here the gist is:
n = '1000'
n = int(n, 2) # convert to int
mask = n
while mask != 0:
mask >>= 1
n ^= mask
CodePudding user response:
The following table shows the conversion of binary code values to gray code values:
Decimal Value | Binary Equivalent | Gray Code Equivalent | Decimal Value of Gray Code Equivalent |
---|---|---|---|
0 | 000 | 000 | 0 |
1 | 001 | 001 | 1 |
2 | 010 | 011 | 3 |
3 | 011 | 010 | 2 |
4 | 100 | 110 | 6 |
5 | 101 | 111 | 7 |
6 | 110 | 101 | 5 |
7 | 111 | 100 | 4 |
Try this code
FROM DECIMAL TO GRAY CODE
def grayCode(n):
# Right Shift the number
# by 1 taking xor with
# original number
return n ^ (n >> 1)
# Driver Code
n = "1000"
print(grayCode(int(n)))
FROM GRAY CODE TO DECIMAL
def inversegrayCode(n):
inv = 0;
# Taking xor until
# n becomes zero
while(n):
inv = inv ^ n;
n = n >> 1;
return inv;
# Driver Code
n = "15";
print(inversegrayCode(int(n)));
source : geeksforgeeks