Reverse the bits of each byte of a string

0

I have a string byte generated by the Random module of the PyCrypto library in this way:

c = Random.new().read(13)

Now, I want to invert the value of the bits that make c with the unary operator ~ , but I can not do it because it is a byte string (apparently I can only use it with int).

For example, if hypothetically the value of the bits that make up 'c' were 1001010 would want to have a byte string whose bits were 0110101 ...

Is there any way to perform the operation and still have a string byte of the same size?

    
asked by Kurosh D. 09.11.2017 в 15:39
source

1 answer

1

I do not know much about PyCrypto but I understand that Random.new().read(13) returns a non-UTF / multibyte string, that is one byte per character. What you can do then is to invert byte x byte in the following way:

from Crypto import Random
c = Random.new().read(13)

inv = "".join([chr(~ord(b) & 0xFF) for b in c])

Let's see:

  • We go through each character of the string c by understanding lists, doing [b for b in c]
  • We convert each character to the number that represents it and we invert it ~ord(b) this would give us a negative number, as the idea is to get another character you have to posit it using the mask 0xFF
  • With the final value we return to generate a character and with the join method we put everything together in an "inverted" string.
answered by 09.11.2017 в 21:43