簡體   English   中英

如何使用python讀取十六進制數據?

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

我有這個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#中相同的枚舉(以提高代碼可讀性)?

十六進制表示法只是一種記錄整數的方法。 您可以在源代碼中輸入0x80 ,也可以將其記為128 ,這對計算機來說意味着相同。

在這方面,Python支持 C 相同的整數文字語法 在類定義上列出相同的屬性,並且具有與枚舉等效的Python:

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

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