I'm trying to take a binary number in string form and flip the 1's and 0's, that is, change all of the 1's in the string to 0's, and all of the 0's to 1's. I'm new to Python and have been racking my brain for several hours now trying to figure it out.
Ways for flipping binary bitsUsing Loops: By iterating each and every bit we check if the bit is 1 if true we change the bit 1 to bit 0 and vice-versa. Using replace() method: In Python, strings have an in-built function replace, which replaces the existing character with a new character.
Thus, minimum flips to make string alternating is 3.
In binary, when we subtract a number A from a number of all 1 bits, what we're doing is inverting the bits of A. So the subtract operation is the equivalent of inverting the bits of the number. Then, we add one.
A simple solution is to use the str. format() function, which performs a string formatting operation. To convert the integer to its binary representation, you can use the string presentation type b .
You've already marked an answer to this, but I haven't seen the method that I would prefer. I'm assuming here that you have a binary number of known length - 8 bits in the examples I am giving.
If you can start with the number as just a number, you can do the following:
myNumber = 0b10010011
myNumberInverted = myNumber ^ 0b11111111
The ^
operator performs a bitwise XOR.
If you really do have to start with a string, you can convert to an integer first and then perform this operation.
myString = '10010011'
myNumber = int(myString, 2)
myNumberInverted = myNumber ^ 0b11111111
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With