Reputation: 153
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)
How can I get the same output in DATA as hex(X_AX)? I need X_AX as one byte HEX for UDP communication.
Current output looks like:
message: b'\x00\x00\x00\x00' ---- 0x0 ---- 0
message: b'\x18\x00\x00\x00' ---- 0x18 ---- 24
X_AX range is -100 to 100
Upvotes: 0
Views: 526
Reputation: 155363
If you want a single byte representation, call struct.pack
with format code b
instead of i
, and it will output a single signed byte (which can represent all values from -128 to 127 inclusive, handling the -100 to 100 range you require). The repr
of said byte in the example case would be b'\x18'
when print
-ed, but when you write
it to a socket or file in binary mode, the raw byte itself would be written.
See the struct
module's format code documentation for other options by size.
Upvotes: 1