Phillip Sloan
Phillip Sloan

Reputation: 125

How to convert integer to 8-digit binary

I am working on this challenge: Challenge #6

I had a working binary and Hamming distance functions, but the binary function just stopped working. It is giving me a

"ValueError: Unknown format code 'b' for object of type 'str'"

error code for some reason. This is the code that I used for both...

# returns only 1's and 0's of binary for int n
def binary(n):
    return '{0:08b}'.format(n)

# returns hamming distance of s1 and s2
def Hamm(s1, s2):
    d = 0   # number of differences between s1 and s2 binary
    for c1, c2 in zip(s1, s2):  # compares s1[x] and s2[x]
        if c1 != c2:
            for a, b in zip(binary(c1), binary(c2)):
                if a != b:
                    d += 1  # if 1 or 0 do not match up, d = d + 1
    print(d)

Upvotes: 0

Views: 2224

Answers (1)

furas
furas

Reputation: 142671

n can be string, not int - ie.

'{0:08b}'.format("1")

and you get error.

So you need int()

'{0:08b}'.format( int(n) )

Upvotes: 1

Related Questions