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
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
On
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
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)))
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
On
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
From RosettaCode:
This takes an
intas input, so you would have to parse the string before calling the function: