I have this c# app that Im trying to cooperate with a app written in python. The c# app send simple commands to the python app, for instance my c# app is sending the following:
[Flags]public enum GameRobotCommands{reset = 0x0,turncenter = 0x1,turnright = 0x2,turnleft = 0x4,standstill = 0x8,moveforward = 0x10,movebackward = 0x20,utility1 = 0x40,utility2 = 0x80}
I'm doing this over TCP and got the TCP up and running, but can I plainly do this in Python to check flags:
if (self.data &= 0x2) == 0x2:#make the robot turn right code
Is there a way in python I can define the same enums that I have in c# (for higher code readability)?
Hexadecimal notation is just that, a way to write down integer numbers. You can enter 0x80
in your source code, or you can write it down as 128
, it means the same thing to the computer.
Python supports the same integer literal syntax as C in that respect; list the same attributes on a class definition and you have the Python equivalent of your enum:
class GameRobotCommands(object):reset = 0x0turncenter = 0x1turnright = 0x2turnleft = 0x4standstill = 0x8moveforward = 0x10movebackward = 0x20utility1 = 0x40utility2 = 0x80
The C# application is probably sending these integers using the standard C byte representations, which you can either interpret using the struct
module, or, if sent as single bytes, with ord()
:
>>> ord('\x80')
128
>>> import struct
>>> struct.unpack('B', '\x80')
(128,)