Ask Your Question
0

inverse binary string bit by bit

asked 2019-10-13 10:54:04 +0200

Hassan Mostafa gravatar image

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 flag offensive close merge delete

Comments

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 ?

tmonteil gravatar imagetmonteil ( 2019-10-13 11:23:25 +0200 )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.

def toggleBit(int_type, offset): mask = 1 << offset return(int_type ^ mask)

Hassan Mostafa gravatar imageHassan Mostafa ( 2019-10-15 11:13:47 +0200 )edit

3 Answers

Sort by ยป oldest newest most voted
0

answered 2019-10-15 11:32:14 +0200

dan_fulea gravatar image

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']
edit flag offensive delete link more
0

answered 2019-10-15 18:48:13 +0200

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'
edit flag offensive delete link more
0

answered 2019-10-16 09:36:10 +0200

You can also use Bitset.

sage: B = Bitset('0110101')
sage: C = Bitset('0' * B.capacity())
sage: for i in range(B.capacity()):
....:     C.add(i)
....:     print(B.symmetric_difference(C))
....:     C.discard(i)
1110101
0010101
0100101
0111101
0110001
0110111
0110100
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2019-10-13 10:54:04 +0200

Seen: 771 times

Last updated: Oct 16 '19