dimanche 16 octobre 2016

How to change 1 bit from a string python?

I generate a 64 bits random string using os.random(8). Next, I want to randomly change the value of one bit of the string getting the bit to change first x = random.getrandbits(6) and doing the XOR operation for that bit like this rand_string ^= 1 << x but this last operation gives me the following error: TypeError: unsupported operand type(s) for ^=: 'str' and 'long'

It's important to me to generate a random binary string because I want to cipher it cipher.encrypt(rand_string) and only takes plain-text for parameters. I don't use random.getrandbits(64) because it returns a long but it doesn't match the 64 bits size block that I want.

Besides, I want to measure the hamming distance between the strings (should give me 1 because I only changed one bit) but I'm afraid that the algorithm I found is not valid to me because it compares the characters representations instead of comparing bit-level:

def hamming_distance(s1, s2):
    # Return the Hamming distance between equal-length sequences
    if len(s1) != len(s2):
        raise ValueError("Undefined for sequences of unequal length")
    return sum(ch1 != ch2 for ch1, ch2 in zip(s1, s2))

So there are two questions:

How could I change randomly a bit of my binary string?

Is the above algorithm valid for my purposes? If it is not, how could I measure the Hamming Distance at bit-level?




Aucun commentaire:

Enregistrer un commentaire