Python3 将一个 INT 转换为 HEX
Python3 Convert one INT to HEX
def convert_output (output):
return (struct.pack('i', output))
while True:
pygame.event.pump()
joystick = pygame.joystick.Joystick(0)
joystick.init()
X_AX = int(joystick.get_axis(0) * 100)
DATA = convert_output(X_AX)
print("message:", (DATA), "----", hex(X_AX), "----", X_AX)
如何在 DATA 中获得与 hex(X_AX) 相同的输出?
我需要 X_AX 作为 UDP 通信的一个字节 HEX。
当前输出如下:
message: b'\x00\x00\x00\x00' ---- 0x0 ---- 0
message: b'\x18\x00\x00\x00' ---- 0x18 ---- 24
X_AX 范围是 -100 到 100
如果你想要一个单字节表示,用格式代码b
而不是i
调用struct.pack
,它会输出一个有符号的字节(它可以表示来自-128 到 127(含),处理您需要的 -100 到 100 范围)。在示例情况下,所述字节的 repr
在 print
-ed 时将是 b'\x18'
,但是当你 write
它以二进制模式发送到套接字或文件时,原始字节本身会被写入。
参见struct
module's format code documentation for other options by size。
def convert_output (output):
return (struct.pack('i', output))
while True:
pygame.event.pump()
joystick = pygame.joystick.Joystick(0)
joystick.init()
X_AX = int(joystick.get_axis(0) * 100)
DATA = convert_output(X_AX)
print("message:", (DATA), "----", hex(X_AX), "----", X_AX)
如何在 DATA 中获得与 hex(X_AX) 相同的输出? 我需要 X_AX 作为 UDP 通信的一个字节 HEX。
当前输出如下:
message: b'\x00\x00\x00\x00' ---- 0x0 ---- 0
message: b'\x18\x00\x00\x00' ---- 0x18 ---- 24
X_AX 范围是 -100 到 100
如果你想要一个单字节表示,用格式代码b
而不是i
调用struct.pack
,它会输出一个有符号的字节(它可以表示来自-128 到 127(含),处理您需要的 -100 到 100 范围)。在示例情况下,所述字节的 repr
在 print
-ed 时将是 b'\x18'
,但是当你 write
它以二进制模式发送到套接字或文件时,原始字节本身会被写入。
参见struct
module's format code documentation for other options by size。