简体   繁体   English

如何使用python读取十六进制数据?

[英]How can I read hexadecimal data with python?

I have this c# app that Im trying to cooperate with a app written in python. 我有这个c#应用程序,我正试图与用python编写的应用程序合作。 The c# app send simple commands to the python app, for instance my c# app is sending the following: C#应用程序向python应用程序发送简单命令,例如我的C#应用​​程序正在发送以下命令:

        [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: 我正在通过TCP进行此操作,并启动了TCP,但可以在Python中明确地检查标志:

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)? python中有没有一种方法可以定义与c#中相同的枚举(以提高代码可读性)?

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. 您可以在源代码中输入0x80 ,也可以将其记为128 ,这对计算机来说意味着相同。

Python supports the same integer literal syntax as C in that respect; 在这方面,Python支持 C 相同的整数文字语法 list the same attributes on a class definition and you have the Python equivalent of your enum: 在类定义上列出相同的属性,并且具有与枚举等效的Python:

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() : C#应用程序可能使用标准C字节表示形式发送这些整数,您可以使用struct模块来解释这些整数,或者如果以单字节形式发送,则可以使用ord()

>>> ord('\x80')
128
>>> import struct
>>> struct.unpack('B', '\x80')
(128,)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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