且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-10-18 21:43:18

十六进制符号只是在t,一种写下整数的方式。您可以在源代码中输入 0x80 ,或者将其写入 128 ,这意味着同样的事情计算机。



Python支持相同的整数文字语法作为C在这方面;列出与类定义相同的属性,并且您的Python等效于您的枚举:

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

C#应用程序可能是使用标准C字节表示,您可以使用 struct module ,或者如果以单个字节发送, ord()

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


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,)