简体   繁体   English

如何将python序列项转换为整数

[英]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. 我需要将python2.7 bytearray()或string或bytes()的元素转换为整数以进行处理。 In many languages(ie C, etc) bytes and 'chars' are more or less 8 bit ints that you an perform math operations on. 在许多语言(例如C等)中,字节和“字符”或多或少是您执行数学运算时要使用的8位整数。 How can I convince python to let me use (appropriate) bytearrays or strings interchangebly? 如何说服python让我交替使用(适当的)字节数组或字符串?

Consider toHex(stringlikeThing): 考虑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: 它将“字符串”转换为十六进制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. “ for”循环中的ord()获取strg [xx],这是一个字节数组,它似乎是一个整数(而str的一个项目是单个元素字符串)所以ord()想要一个char(单个)元素字符串)不是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? 是否有一些方法或函数接受一个字节,char,small int,一个元素字符串的参数并返回其值?


Of course you could check the type(strg[xx]) and handle the cases laboriously. 当然,您可以检查类型(strg [xx])并费力地处理案件。

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)? 清晰的问题是:为什么Python这么挑剔地看待字节和char(普通或unicode)(即单元素字符串)之间的差异?

When you index a bytearray object in python, you get an integer. 当您在python中为bytearray对象建立索引时,会得到一个整数。 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. 该整数是字节数组中相应字符的代码,或者说是ord函数将返回的内容。

There is no method in python that takes a byte, character, small integer, or one element string and returns it's value in python. python中没有方法采用字节,字符,小整数或一个元素字符串并在python中返回其值。 Making such a method would be simple however. 但是,制作这种方法将很简单。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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