对C数据类型的python按位运算?

时间:2011-08-18 18:53:07

标签: python bit-manipulation ctypes

是否可以在Python中对C数据类型执行按位操作?

Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) 
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from ctypes import c_uint8
>>> foo = c_uint8(4)
>>> foo << 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for <<: 'c_ubyte' and 'int'
>>>

3 个答案:

答案 0 :(得分:3)

尝试foo.value << 1

或更新foo,

foo.value <<= 1

答案 1 :(得分:2)

这样可行,但不是在C级别完成:

foo.value << 1

答案 2 :(得分:1)

from ctypes import c_uint8
foo = c_uint8(4)
print foo.value << 1

将根据需要打印8。要更改foo,请使用

foo.value <<= 1