如何在Python中将多个整数转换为c_字节的ctypes数组
如何将以冒号分隔的十六进制数字字符串转换为c_ubyte的ctypes数组?根据,我可以铸造一个硬编码的集合,如下所示:如何在Python中将多个整数转换为c_字节的ctypes数组,python,types,casting,initialization,ctypes,Python,Types,Casting,Initialization,Ctypes,如何将以冒号分隔的十六进制数字字符串转换为c_ubyte的ctypes数组?根据,我可以铸造一个硬编码的集合,如下所示: >>> from ctypes import * >>> x = (c_ubyte * 6) (1, 2, 3, 4, 5, 6) >>> x <__main__.c_ubyte_Array_6 object at 0x480c5348> >>> XObj = c_ubyte * 6 >
>>> from ctypes import *
>>> x = (c_ubyte * 6) (1, 2, 3, 4, 5, 6)
>>> x
<__main__.c_ubyte_Array_6 object at 0x480c5348>
>>> XObj = c_ubyte * 6
>>> x = XObj(1, 2, 3, 4, 5, 6)
>>> x
<__main__.c_ubyte_Array_6 object at 0x480c53a0>
>>从ctypes导入*
>>>x=(c_ubyte*6)(1,2,3,4,5,6)
>>>x
或者,像这样:
>>> from ctypes import *
>>> x = (c_ubyte * 6) (1, 2, 3, 4, 5, 6)
>>> x
<__main__.c_ubyte_Array_6 object at 0x480c5348>
>>> XObj = c_ubyte * 6
>>> x = XObj(1, 2, 3, 4, 5, 6)
>>> x
<__main__.c_ubyte_Array_6 object at 0x480c53a0>
XObj=c_ubyte*6
>>>x=XObj(1,2,3,4,5,6)
>>>x
但是,我不知道如何强制转换变量列表,例如通过拆分字符串生成的变量列表,例如:
>>> mac = 'aa:bb:cc:dd:ee:ff'
>>> j = tuple(int(z,16) for z in mac.split(':'))
>>> j
(170, 187, 204, 221, 238, 255)
>>> x = (c_ubyte * 6) (j)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: an integer is required
>>> XObj = c_ubyte * 6
>>> x = XObj(j)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: an integer is required
mac='aa:bb:cc:dd:ee:ff'
>>>j=mac.split(“:”)中z的元组(int(z,16)
>>>j
(170, 187, 204, 221, 238, 255)
>>>x=(c_ubyte*6)(j)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:需要一个整数
>>>XObj=c_ubyte*6
>>>x=XObj(j)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:需要一个整数
我错过了什么
谢谢 问题在于,在您提供的第一个示例中,通过为XObj调用提供6个参数,您正确地使用了ctypes,而在第二个示例中(使用mac地址),您尝试调用相同的对象
c_ubyte*6
,给它一个元组,但不是6个值,因此使用*args
表示法对其进行转换:
from c_types import c_ubyte
mac = 'aa:bb:cc:dd:ee:ff'
j = tuple(int(z,16) for z in mac.split(':'))
converted = (c_ubyte * 6)(*j) # *j here is the most signigicant part
print converted
结果是:
<__main__.c_ubyte_Array_6 object at 0x018BD300>
正如所料。问题在于,在您提供的第一个示例中,您通过为XObj调用提供6个参数正确使用了ctypes,而在第二个示例中(使用mac地址),您尝试调用同一个对象
c_ubyte*6
,给它一个元组,但不是6个值,因此使用*args
表示法对其进行转换:
from c_types import c_ubyte
mac = 'aa:bb:cc:dd:ee:ff'
j = tuple(int(z,16) for z in mac.split(':'))
converted = (c_ubyte * 6)(*j) # *j here is the most signigicant part
print converted
结果是:
<__main__.c_ubyte_Array_6 object at 0x018BD300>
果然如此。谢谢!这正是我需要的。顺便说一句,您是否会更新您的答案,使其包含用于拆分、解析字符串并将其转换为c_ubyte数组的单行版本?像这样:
x=(c_ubyte*6)(*tuple(int(z,16)代表“aa:bb:cc:dd:ee:ff”中的z.split(“:”))
@Trevor,我不是一个代码完整的程序,我更喜欢可读性;)很公平。也许是我的Perl教育让我一直追求简洁。:)不管怎样,你的答案正是我需要的。谢谢谢谢这正是我需要的。顺便说一句,您是否会更新您的答案,使其包含用于拆分、解析字符串并将其转换为c_ubyte数组的单行版本?像这样:x=(c_ubyte*6)(*tuple(int(z,16)代表“aa:bb:cc:dd:ee:ff”中的z.split(“:”))
@Trevor,我不是一个代码完整的程序,我更喜欢可读性;)很公平。也许是我的Perl教育让我一直追求简洁。:)不管怎样,你的答案正是我需要的。谢谢