string - How do you convert a python sequence item to an integer -


i need convert elements of python2.7 bytearray() or string or bytes() integers processing. in many languages(ie c, etc) bytes , 'chars' more or less 8 bit ints perform math operations on. how can convince python let me use (appropriate) bytearrays or strings interchangebly?

consider tohex(stringlikething):

zerof = '0123456789abcdef' def tohex(strg):     ba = bytearray(len(strg)*2)     xx in range(len(strg)):         vv = ord(strg[xx])         ba[xx*2] = zerof[vv>>4]         ba[xx*2+1] = zerof[vv&0xf]     return ba 

which should take string thing (ie bytearray or string) , make printable string thing of hexadecimal text. converts "string" hex ascii:

>>> tohex("string") bytearray(b'737472696e67') 

however, when given bytearray:

>>> nobcom.tohex(bytearray("bytes")) ex ord() expected string of length 1, int found: 0 bytes 

the ord() in 'for' loop gets strg[xx], item of bytearray, seems integer (whereas item of str single element string) ord() wants char (single element string) not int.

is there method or function takes argument byte, char, small int, 1 element string , returns it's value?


of course check type(strg[xx]) , handle cases laboriously.

the unvoiced question is: why (what reasoning) python picky difference between byte , char (normal or unicode) (ie single element string)?

when index bytearray object in python, integer. integer code corresponding character in bytearray, or in other words, thing ord function return.

there no method in python takes byte, character, small integer, or 1 element string , returns it's value in python. making such method simple however.

def toint(x):      return x if type(x) == int else ord(x) 

Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -