thethiny
thethiny

Reputation: 1248

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?

Upvotes: 14

Views: 32081

Answers (4)

Senyai
Senyai

Reputation: 1635

>>> map("{:02x}".format, (10, 13, 15))
['0a', '0d', '0f']

Upvotes: 19

Andrew Clark
Andrew Clark

Reputation: 208545

This is happening because hex() will not include any leading zeros, for example:

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

To make sure you always get two characters, you can use str.zfill() to add a leading zero when necessary:

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

Upvotes: 30

Torxed
Torxed

Reputation: 23490

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?

Upvotes: 0

Joran Beasley
Joran Beasley

Reputation: 114038

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

note that this would still remove the leading 0's from things with more than 2 hex values eg: "0x%02x"%0x0055 => "0x55"

Upvotes: 2

Related Questions