аватар question@mail.ru · 01.01.1970 03:00

Coding of the text into an arbitrary binary code and vice versa. Example: "A" <-> "01100011"

I need to convert the line, for example "A" ", into a line of binary code, for example " "01100011" ", then process a slightly binary code, passing it according to the function" "excluding or" with another double code, for example, for example "" 01100011 "" with "11000010" ", then " "10100001" "", and back the resulting code to the readable line, for example, in "" t .

This, I want to use Russian, English and Ukrainian layout and numbers, with signs of reproaching. Do not tell me how to do this on Python 3?

The question is how to convert a line into a binary code and vice versa using any encoding algorithm?

аватар answer@mail.ru · 01.01.1970 03:00

To tu the arbitrary text into "01"-Lines (Bits):

   def   text_to_Bits  ( text, encoding =  'utf-8' , errors =  '> Surrogatepass'  ):  bits =  bin  ( into  .from_bytes (text.encode (Encoding, errors).  'big' )) [ 2 :]   retu  bits.zfill ( 8  * (( len  (bits) +  7 ) //  8 ))     

and vice versa:

   def   text_from_bits  ( bits, encuding =  'UTF-8' , errors =  'suhrogatepass'  ):  n =  int  (bits,  2 )    retu  n.to_bytes ((n.bit_length () +  7 ) //  8 ,  'big' ). Decode (encoding, errors)  or   '' \ 0 '  

& gt; & gt; & gt; Text_to_Bits ())) '"1101000011111111111110111110000000' & gt; & gt; & gt; text_from_Bits (_) mir

see. .


To perform the xor above two lines, there is no need to express the bits in the form of an asci-string:

   FROM  Import  cycle  def   xor  message, key ):   retu   bytes  (a^b  for  a, b  in   zip  (Message, Cycle (Key)))     

Enough the text in bytes, using .encode () Method:

  & gt; & gt; & gt;  key =  b'Key '   & gt; & gt; & gt;  xor ( 'Hello World'  .encode (), key)   b '\ x03 \ x00 \ x15 \ x07 \ ny \ x1c \ n \ x0b \ x07 \ x01'    & gt; & gt;  xor (_, key) .Decode () # and vice versa    'Hello World'      

cm. .

for large lines, you can use numpy:

   import  numpy  as  np # pip install numpy    def   slow_xor  ( aa, aa, aa, aa, aa, bb ):  a = np.frombuffer (aa, dtype = np.byte)  b = np.frombuffer (bb, dtype = np.byte)   retu  np.bitwise_xor (a, a, a, a, a, a, a, a, b) .tostring ()  

Example:

   & gt; & gt;  Slow_xor ( b'hello ... ',  .encode ())   b '\ xb8 \ xd9 \ xbc \ xd4 \ xbe \ xae \ xff \ xa4'      

if you want to accelerate this function, see.

Latest

Similar