如何用python读取十六进制数据? [英] How can I read hexadecimal data with python?
问题描述
[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:
#机器人右转代码
有没有办法在python中我可以定义与c#中相同的枚举(更高的代码可读性)?
十六进制符号只是在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,)
这篇关于如何用python读取十六进制数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!