14

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?

thethiny
  • 1,125
  • 1
  • 10
  • 26

4 Answers4

30

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)
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
  • ` for i in b[0x15c:0x15f]: h = hex(ord(i))[2:] if len(h) != 2: h = '0'+h fc += h;` A friend told this will work – thethiny Apr 08 '13 at 17:25
  • At last, a properly explained worked example on this ! – monojohnny Dec 01 '15 at 22:14
  • I wouldn't say its properly explained and I'm not the best to explain. Its ignoring the leading zeros because they mean nothing towards the decimal value of the hex values. They indicate the number of bytes the values takes up. 15 = f. 0f = 15 because 0 + 15 is 15 – Daniel Cull Jan 03 '18 at 15:04
19
>>> map("{:02x}".format, (10, 13, 15))
['0a', '0d', '0f']
Senyai
  • 1,395
  • 1
  • 17
  • 26
2
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"

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
0

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?

Community
  • 1
  • 1
Torxed
  • 22,866
  • 14
  • 82
  • 131
  • 1
    no , it is stripped from the data , I tried printing the output , and it gives different values , 04f is way too much different than 00040f – thethiny Apr 08 '13 at 17:32