user6573621
user6573621

Reputation:

How to flip a pattern of bits in binary representation?

I have a String like this BGGBG. Now i have to flip all BG to GB.In this string there is two BG's.Now if i want to represent it as Binary(taking B=0 and G=1) then it would be 01101. So from this want to flip 01 to 10. Is this possible to do? if yes How can it be done in Python?

FYI: This is not just flipping bits(0 to 1 and vice versa).Rather it has to do with flipping a pattern(like 01 in this case).

I know i could have just used str.replace() like this:

string=string.replace("BG","GB") # will replace all BG to GB

Actually this can be a decent approach to solve this problem here at codeforces. https://codeforces.com/problemset/problem/266/B

Upvotes: 2

Views: 279

Answers (2)

AShelly
AShelly

Reputation: 35520

If your binary string is in bg: this sets mask to 1 only in the positions where bg has a 01. The 1s are doubled in flip, and XORd with the original to get the result:

>>> bg = 0b00011011
>>> mask = bg & (~bg>>1)
>>> flip = mask|mask<<1
>>> result = bg ^ flip
>>> bin(result)
'0b00101101'

Upvotes: 1

Florian Wendelborn
Florian Wendelborn

Reputation: 1747

I’m not suggesting that this is the best, most sustainable, or even an acceptable way to do it, but it certainly was fun writing this. I hope it brings you closer to solving what you’re trying to solve:

import re

# I’m assuming that the string is "((BG)*(GB)*)*"
# any other characters will make this fail
input = 'BGBGBGGBGBGB'
output = ''

for two in re.findall('..', input):
    output += int.to_bytes(int.from_bytes(two.encode(), 'big') ^ 1285, 2, 'big').decode('ascii')

print(input)
print(output)

Upvotes: 1

Related Questions