0

I wrote a program to convert binary code to Gray code using only string operation. I want to check the feasibility of my code and also whether it's the right or wrong approach.

def binary_to_gray(x):
    x = str(x)
    gray = x[0]
    for i in range(len(x) - 1):
        if (x[i] == x[i + 1]):
            gray += "0"
        else :
            gray += "1"
karel
  • 5,489
  • 46
  • 45
  • 50
  • Write a binary counter loop. Store the current and previous gray values. Perform an xor on them. Check that only 1 bit is ever set in the xor. Some C code for the 1bit set (or power of 2) check https://www.exploringbinary.com/ten-ways-to-check-if-an-integer-is-a-power-of-two-in-c/ – Paul Floyd Sep 12 '19 at 14:33
  • You may want to check: https://marcin-chwedczuk.github.io/binary-to-gray-algorithm-explained – csharpfolk Dec 18 '19 at 08:52

0 Answers0