简体   繁体   English

Python,Printing Hex首先删除0?

[英]Python , Printing Hex removes first 0?

take a look at this: 看看这个:

fc = '0x'
for i in b[0x15c:0x15f]:
    fc += hex(ord(i))[2:]

Lets say this code found the hex 00 04 0f , instead of writing it that way , it removes the first 0 , and writes : 04f any help? 让我们说这段代码找到了十六进制00 04 0f,而不是那样写,它删除了第一个0,并写道:04f任何帮助?

This is happening because hex() will not include any leading zeros, for example: 发生这种情况是因为hex()不包含任何前导零,例如:

>>> hex(15)[2:]
'f'

To make sure you always get two characters, you can use str.zfill() to add a leading zero when necessary: 要确保始终获得两个字符,可以使用str.zfill()在必要时添加前导零:

>>> hex(15)[2:].zfill(2)
'0f'

Here is what it would look like in your code: 以下是您的代码中的样子:

fc = '0x'
for i in b[0x15c:0x15f]:
    fc += hex(ord(i))[2:].zfill(2)
>>> map("{:02x}".format, (10, 13, 15))
['0a', '0d', '0f']
print ["0x%02x"%ord(i) for i in b[0x15c:0x15f]]

use a format string "%2x" tells it to format it to be 2 characters wide, likewise "%02x" tells it to pad with 0's 使用格式字符串"%2x"告诉它将其格式化为2个字符宽,同样"%02x"告诉它用0填充

note that this would still remove the leading 0's from things with more than 2 hex values eg: "0x%02x"%0x0055 => "0x55" 请注意,这仍将从超过2个十六进制值的事物中删除前导0,例如: "0x%02x"%0x0055 => "0x55"

It's still just a graphical representation for your convenience. 为了您的方便,它仍然只是一个图形表示。
The value is not actually stripped from the data, it's just visually shortened. 该值实际上并未从数据中删除,只是在视觉上缩短了。

Full description here and why it is or why it's not important: Why are hexadecimal numbers prefixed with 0x? 这里有完整的描述,为什么它或为什么它不重要: 为什么十六进制数字前缀为0x?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM