我正在鑽研C,因爲我需要將ctypes庫導入到python以允許鍵盤控制。我努力學習下面的代碼是如何工作的:C - 簽名和無符號整數
import ctypes
import time
SendInput = ctypes.windll.user32.SendInput
# C struct redefinitions
PUL = ctypes.POINTER(ctypes.c_ulong)
class KeyBdInput(ctypes.Structure):
_fields_ = [("wVk", ctypes.c_ushort),
("wScan", ctypes.c_ushort),
("dwFlags", ctypes.c_ulong),
("time", ctypes.c_ulong),
("dwExtraInfo", PUL)]
class HardwareInput(ctypes.Structure):
_fields_ = [("uMsg", ctypes.c_ulong),
("wParamL", ctypes.c_short),
("wParamH", ctypes.c_ushort)]
class MouseInput(ctypes.Structure):
_fields_ = [("dx", ctypes.c_long),
("dy", ctypes.c_long),
("mouseData", ctypes.c_ulong),
("dwFlags", ctypes.c_ulong),
("time",ctypes.c_ulong),
("dwExtraInfo", PUL)]
class Input_I(ctypes.Union):
_fields_ = [("ki", KeyBdInput),
("mi", MouseInput),
("hi", HardwareInput)]
class Input(ctypes.Structure):
_fields_ = [("type", ctypes.c_ulong),
("ii", Input_I)]
# Actuals Functions
def PressKey(hexKeyCode):
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.ki = KeyBdInput(hexKeyCode, 0x48, 0, 0, ctypes.pointer(extra))
x = Input(ctypes.c_ulong(1), ii_)
SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
def ReleaseKey(hexKeyCode):
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.ki = KeyBdInput(hexKeyCode, 0x48, 0x0002, 0, ctypes.pointer(extra))
x = Input(ctypes.c_ulong(1), ii_)
SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
def AltTab():
'''
Press Alt+Tab and hold Alt key for 2 seconds in order to see the overlay
'''
PressKey(0x012) #Alt
PressKey(0x09) #Tab
ReleaseKey(0x09) #~Tab
time.sleep(2)
ReleaseKey(0x012) #~Alt
if __name__ =="__main__":
AltTab()
我不理解有關符號和無符號整數部分:
INT射程爲-32768 - 32767
unsigned int的取值範圍爲0 - 65535
我讀到:「由於您有16位可以表示數字,所以可以用2字節數顯示的數字的總範圍是2^16^2^16與65536相同,因爲我們從0開始計數,與0 - 65535相同。這顯然與一個unsigned int值相匹配,所以你可以看到,這是多麼這種類型的操作「
這似乎是有道理的,但有一件事我不明白:
1字節= 8位 2個字節= 16位
那麼爲什麼2字節數被稱爲2^16而不是2^8?
,因爲它有16位。每個位可以容納2個值,因此2^16個可能的數字與2個字節 – pippin1289
啊當然,謝謝。 – Phoenix
注意:根據C,[byte](http://en.wikipedia.org/wiki/Byte#Common_uses)至少爲8位。 – chux