I need help with a python version for this C code:
#define HostBusy_high 0x02
#define control_register 0x37a
Out32 (control_register,(unsigned char)(Inp32(control_regi开发者_如何学Pythonster) | HostBusy_high));
the Out32 and Inp32 are functions located in the inpout32.dll used to interface parallel ports. These functions take hex values as their parameters. I tried to code in python to get the desired value but that is not what I am getting. See python version below:
from ctypes import windll
#parallel port instance
p_port = windll.inpout32
HostBusy_high = 0x02
control_register = 0x37a
write_data = write(p_port(Inp32(control_register) | HostBusy_high))
Out32 (control_register,write_data))
With the code above i do not seem to get the value I want. I suspect it is the unsigned value.
Thanks
Depends on why you need an unsigned char. For most purposes you'll just use a Python integer. If you need to actually have a one-byte datum, you can use Python's struct.pack to make a one-byte byte string out of an integer.
You can't, in general, get good results by doing line by line literal translation of code between languages, without a good understanding of both the source and target languages, as well as the body of code you're translating.
Maybe you just should get the modulo 256 of your value. Then it is surely unsigned. Examples:
>>> 12 % 256
12
>>> 1022 % 256
254
>>> -1 % 256
255
>>> -127 % 256
129
You can find a match in the ctypes library with the c_ubyte
data type. See if you populate an object of that type with your value and find if its suitable.
https://docs.python.org/3/library/ctypes.html#ctypes.c_ubyte
The rest of the types are tabulated in https://docs.python.org/3/library/ctypes.html#fundamental-data-types
精彩评论