First time here? Check out the FAQ!

Ask Your Question
0

inverse binary string bit by bit

asked 5 years ago

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.

Preview: (hide)

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 ( 5 years ago )

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 ( 5 years ago )

3 Answers

Sort by » oldest newest most voted
0

answered 5 years ago

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']
Preview: (hide)
link
0

answered 5 years ago

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'
Preview: (hide)
link
0

answered 5 years ago

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
Preview: (hide)
link

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: 5 years ago

Seen: 934 times

Last updated: Oct 16 '19