Tuesday, 15 February 2011

python - encrypting a string via binary manipulation -



python - encrypting a string via binary manipulation -

i'm running problem involving encrypting strings. i'm doing converting each letter numbers using ord() function , converting binary codes. invert or xor numbers letter 'a' have binary code of '0100 0001' become '1011 1110' when converted decimal value 190, chr() letter. i've noticed letters don't convert symbols can seen @ all. when tried convert decimal value of 157 ascii character. got '\x9d' instead of ascii value. according extended ascii codes, should have given me symbol can read print function , print file. there way create python print readable symbol can print it? right i'm unable create work due inability of programme print symbols can read , reverse process.

python defaults showing representation of strings unless explicitly print them. \x9d repr (representation) of character, if print see else depending on encoding , font terminal uses

>>> chr(157) '\x9d' >>> print repr(chr(157)) # equivalent above '\x9d' >>> print chr(157) � # appears question mark in diamond shaped box on scheme

this doesn't stop writing info file though.

edit

if "extended ascii" referring character set http://en.wikipedia.org/wiki/code_page_437, should able use

>>> print chr(157).decode('cp437') ¥

this returns unicode string suitable printing (if terminal supports that).

edit 2

it's little different in python 3.x ord returns unicode str. instead want bytes str (which equivalent python2.x str):

>>> bytes([157]) # equivalent ord(157) in python 2.x b'\x9d' >>> bytes([157]).decode('cp437') # decode unicode str desired encoding '¥' >>> print(bytes([157]).decode('cp437')) # it's suitable printing ¥

make sure when write info file write raw bytes str, not unicode (printable) str:

>>> info = bytes([154, 155, 156, 157]) >>> print (data.decode('cp437')) # utilize decode printing Ü¢£¥ >>> open('output.dat', 'wb') f: ... f.write(data) # not writing file ... 4 >>> open('output.dat', 'rb') f: ... info = f.read() ... print(data) ... print(data.decode('cp437')) ... b'\x9a\x9b\x9c\x9d' Ü¢£¥

python string binary

No comments:

Post a Comment