How to cast binary into a string in python -


for infosec projects i'm using strings kind of byte array. commonly done in vulnerability testing. in building byte array, want concatenate printable characters , nonprintable characters.

this not question of conversion, want cast type. write function or method around chr(), there must better way.

>>> print "a"*10 + chr(0x20) + "b"*10 aaaaaaaaaa bbbbbbbbbb 

e.g., if have large binary array insert?

>>> print "a"*10 + 0xbeef + "b"*10 traceback (most recent call last):   file "<stdin>", line 1, in <module> typeerror: cannot concatenate 'str' , 'int' objects  >>> print "a"*10 + 0xbeefbeefbeefbeefbeefbeef + "b"*10 traceback (most recent call last):   file "<stdin>", line 1, in <module> typeerror: cannot concatenate 'str' , 'long' objects 

i may using wrong data types here because i'm pretty sure i'm not guaranteed strings have 8-bit bytes.


an example of hope for:

>>> print "a"*10 + 0xbeefbeefbeefbeefbeefbeef + "b"*10 aaaaaaaaaa������������bbbbbbbbbb 

you can use binascii.unhexlify if it's bit of chore type out escaped hexadecimals in string, eg:

from binascii import unhexlify  b = 'a'*10 + unhexlify('beef' * 6) + 'b'*10 # 'aaaaaaaaaa\xbe\xef\xbe\xef\xbe\xef\xbe\xef\xbe\xef\xbe\xefbbbbbbbbbb' 

in python 3 though, you'd have make sure start byte strings (or you'll receive typeerror: can't convert 'bytes' object str implicitly):

b'a'*10 + unhexlify('beef' * 6) + b'b'*10 # b'aaaaaaaaaa\xbe\xef\xbe\xef\xbe\xef\xbe\xef\xbe\xef\xbe\xefbbbbbbbbbb' 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -