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

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

<p>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:</p>

<pre><code>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))
</code></pre>

<p>So there are two questions:</p>

<p>How could I change randomly a bit of my binary string?</p>

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

<p>I do not see the point in getting random bits and than lshifting. A randInt should do just right. Also if you want to change a single bit, try to xor a character instead of the string. If that does not work <code>...=chr(ord(char)^x)</code></p>

python python-2.7 random bit-manipulation