简体   繁体   中英

How can I read hexadecimal data with python?

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 = 0x0
    turncenter = 0x1
    turnright = 0x2
    turnleft = 0x4
    standstill = 0x8
    moveforward = 0x10
    movebackward = 0x20
    utility1 = 0x40
    utility2 = 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,)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM