jazzer97
jazzer97

Reputation: 157

Flipping bits from 0 to 1

I have a bit string represented by

011

and I want to flip the bit at index zero to 1 which would give me:

111

Because python doesn't allow me to represent the bit using integer where initially i planned:

mybit = 011

which gives me an error for some error. So the only way i found was to use string to represent it:

mybit = "011"

but since string is immutable, i couldn't figure out any ways to flip the 0 at index 0 to 1. Creating a new string from scratch does not seem feasible as it doesn't look like I'm flipping it. Would appreciate some help on this

Upvotes: 1

Views: 2269

Answers (1)

kindall
kindall

Reputation: 184081

You were on the right track. Represent it as an integer.

mybit = 0b011

Flip bits using ^ (bitwise xor) operator. Bits that are 1 in the second operand will be flipped.

mybit ^= 0b100

Set bits (even if already set) using | (bitwise or). Bits that are 1 in the second operand will be set.

mybit |= 0b100

Clear bits (even if already clear) using & (bitwise and). Bits that are 0 in the second operand will be cleared.

mybit &= 0b011

Print in binary format.

print(bin(mybit))

Upvotes: 4

Related Questions