# inverse binary string bit by bit

if i have a binary string for example x='0110101' and i need to inverse it's bits bit by bit. for example : inverse 1st bit >> x='1110101' inverse 2nd bit >> x='0010101' 3rd bit >> x='0100101'

and so on. how can i do that.

edit retag close merge delete

This looks like homework. Could you please tell us how it is related to Sage, and what were your attempts in solving this ? For example, why are you using a string and not a list of integers ?

( 2019-10-13 11:23:25 +0100 )edit

no it is not a homework. it is related to sage as for example i am working with cryptography >> Rijndael-GF block cipher which sometimes i need to use binary key, message and ciphers. anyway i've found a function that do this role as following; # toggleBit() returns an integer with the bit at 'offset' inverted, 0 -> 1 and 1 -> 0.

( 2019-10-15 11:13:47 +0100 )edit

Sort by ยป oldest newest most voted

For instance, using list comprehension:

sage: x = '0110101'
sage: R = range(len(x))
sage: def show_bit(s, exchange=False):
....:     if not exchange:
....:         return s
....:     return str(1-int(s))
....:
sage: [ ''.join([show_bit(x[j], j <= k) for j in R]) for k in R ]


This gives the list of the path of the strings where one by one the bits are reverted:

['1110101', '1010101', '1000101', '1001101', '1001001', '1001011', '1001010']

more

You could just use Python string replacement: https://docs.python.org/2/library/std.... Replace every "0" with "x", then replace every "1" with "0", then replace every "x" with "1". Or use the translatemethod: https://docs.python.org/2/library/std...: create a translation table swapping 0 and 1 and then apply it. In Python 2:

sage: import string
sage: T = string.maketrans('01', '10')
sage: s = '00111'
sage: s.translate(T)
'11000'


In Python 3:

sage: T = str.maketrans({'0': '1', '1': '0'})
sage: s = '00111'
sage: s.translate(T)
'11000'

more

You can also use Bitset.

sage: B = Bitset('0110101')
sage: C = Bitset('0' * B.capacity())
sage: for i in range(B.capacity()):
....:     print(B.symmetric_difference(C))
1110101
0010101
0100101
0111101
0110001
0110111
0110100

more