Monday, 15 July 2013

python - How to convert a word in string to binary -


I was working on a module ( import module stuff) to convert words String (and if possible, octets) on hex and binary will help. I had finished the hex part. But now I am struggling in the case of binary. I do not know where to start or what to do. What I want to do is simple. It will take an input string such as 'test' . The function inside the module will convert it into binary.

What I have done so far is given below:

  def string_hex (string): #hex keyword = string.encode () to import a word Converts binascii hexadecimal = str (binascii.hexlify) (keyword), 'ASCI') formatted_hex = ':'. For the category (i, i, i + 2) in the range (0, lane (hexadecimal), 2) Return formatted_hex def hex_string (hexa): #hexa (seeing this name as it contains a built-in function hex ()) Should be written as a string. The symbols are accurately denoted by words (,!!), String = by Tes.fromhex (hexa) formatted_string = string.decode () return formatted_string  

I saved it in that directory where I used to name my dragon In this way I call it in experiment.py .

  & gt; & Gt; & Gt; String_hex from experiment import & gt; & Gt; & Gt; String_hex '74: 65: 73: 74' ' 

Just like this I can also convert it back to:

  & Gt; & Gt; & Gt; Hex_string from experiment import & gt; & Gt; & Gt; Hex_String ('74657374') 'test'  

As soon as the word wanted to change the binary in the string. And one more thing i python 3.4.2 please help me.

You can do this as follows. You do not even need to import binascii .

  def string_hex (string): return ':'. Include (0, lane (hexa), 2) for hex_string (hexa): hexgen = (hexa [i: i + 2] i range in format (ord (c), 'x' c) ) Return to 'join' (def (ord (c), 'b' in the string) '' .join (for chr (eval ('0x' b '(binary): bingen = (binary [])) I: i + 7] Returns for 'i' category (0, lane (binary), 7)). For n in Bingen (chr (eval ('0b' + n))  

And here is the output:

  gt;> String_hex ('test') '74: 65: 73: 74'>>>> Hex_string ('74657374' ) 'Testing'> String_bin ('test') '1110100: 1100101: 1110011: 1110100' & gt; & gt; Bin_string ('111010011 0010111100111110100 ')' test ' 

No comments:

Post a Comment