简体   繁体   中英

How do you convert a python sequence item to an integer

I need to convert the elements of a python2.7 bytearray() or string or bytes() into integers for processing. In many languages(ie C, etc) bytes and 'chars' are more or less 8 bit ints that you an perform math operations on. How can I convince python to let me use (appropriate) bytearrays or strings interchangebly?

Consider toHex(stringlikeThing):

zerof = '0123456789ABCDEF'
def toHex(strg):
    ba = bytearray(len(strg)*2)
    for 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 a string like thing (ie bytearray or string) and make a printable string like thing of hexadecimal text. It converts "string" to the hex ASCII:

>>> toHex("string")
bytearray(b'737472696E67')

However, when given a bytearray:

>>> nobCom.toHex(bytearray("bytes"))
EX ord() expected string of length 1, but int found: 0 bytes

The ord() in the 'for' loop gets strg[xx], an item of a bytearray, which seems to be an integer (Whereas an item of a str is a single element string) So ord() wants a char (single element string) not an int.

Is there some method or function that takes an argument that is a byte, char, small int, one element string and returns it's value?


Of course you could check the type(strg[xx]) and handle the cases laboriously.

The unvoiced question is: Why (what is the reasoning) for Python to be so picky about the difference between a byte and char (normal or unicode) (ie single element string)?

When you index a bytearray object in python, you get an integer. This integer is the code for the corresponding character in the bytearray, or in other words, the very thing that the ord function would return.

There is no method in python that takes a byte, character, small integer, or one element string and returns it's value in python. Making such a method would be simple however.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM