【问题标题】:How can I read hexadecimal data with python?如何使用 python 读取十六进制数据?
【发布时间】:2012-08-03 07:25:37
【问题描述】:

我有这个 c# 应用程序,我试图与一个用 python 编写的应用程序合作。 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
        }

我正在通过 TCP 执行此操作并启动并运行 TCP,但我可以在 Python 中明确执行此操作以检查标志:

if (self.data &= 0x2) == 0x2:
    #make the robot turn right code

有没有一种方法可以在 python 中定义与 c# 中相同的枚举(以获得更高的代码可读性)?

【问题讨论】:

  • 标题相当具有误导性 - 您实际搜索的是“python 中的枚举”,不是吗?
  • 他正在寻找一种实现位域的方法。

标签: python enums flags


【解决方案1】:

十六进制符号就是这样,一种写下整数的方法。可以在源代码中输入0x80,也可以写成128,对电脑来说是一样的意思。

Python 在这方面支持same integer literal syntax 作为C;在类定义中列出相同的属性,并且您拥有与枚举等效的 Python:

class GameRobotCommands(object):
    reset = 0x0
    turncenter = 0x1
    turnright = 0x2
    turnleft = 0x4
    standstill = 0x8
    moveforward = 0x10
    movebackward = 0x20
    utility1 = 0x40
    utility2 = 0x80

C# 应用程序可能使用standard C byte representations 发送这些整数,您可以使用struct module 解释它们,或者,如果作为单个字节发送,则使用ord()

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-18
    • 1970-01-01
    • 2021-09-24
    • 2015-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多