Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Flipping Binary 1's and 0's in a String

Tags:

python

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.

like image 898
Just a Student Avatar asked Oct 13 '10 03:10

Just a Student


People also ask

How do you flip binary in Python?

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.

How many minimum numbers of bits should be flipped in a string containing 0's and 1's such that 0's and 1's should be alternate?

Thus, minimum flips to make string alternating is 3.

How do you invert a binary number?

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.

How do you convert a binary number to a string in Python?

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 .


1 Answers

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
like image 54
Ian Avatar answered Sep 27 '22 18:09

Ian