pythonvalidationintegerconvertersgray-code

Python GrayCode saved as string directly to decimal


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


Solution

  • 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)))