擅长:python、mysql、java
<p>(编辑:我的疏忽。请参阅<a href="https://stackoverflow.com/a/26283443/923794">Rob's answer</a>以正确覆盖负号)</p>
<p>如果只想将十六进制字符串转换为int,请执行以下操作:</p>
<pre><code>>>> int('0xff', 16)
255
>>> int('0xdaad', 16)
55981
</code></pre>
<p>相反,可以使用<code>hex()</code>函数来完成。从帮助页:</p>
<p>内置函数十六进制模块内置帮助:</p>
<pre><code>>>> help(hex)
hex(...)
hex(number) -> string
Return the hexadecimal representation of an integer.
>>> hex(3735928559)
'0xdeadbeef'
</code></pre>
<p>如果数据流中缺少“x”,则删除或添加它应该很简单。
下面是一个确保填充到6个字符(表示3个字节=24位)的示例:</p>
<pre><code>>>> '0x' + hex(255)[2:].rjust(6, '0')
'0x0000ff'
</code></pre>
<p>如果您以3字节(24位)的形式获取数据,则可以使用<code>int.to_bytes()</code>和<code>int.from_bytes()</code>,如<a href="https://docs.python.org/3/library/stdtypes.html#additional-methods-on-integer-types" rel="nofollow noreferrer">the Python docs</a>中所述。这是Python3.2中的新功能。</p>