Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python , Printing Hex removes first 0?

Tags:

python

hex

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?

like image 536
thethiny Avatar asked Apr 08 '13 16:04

thethiny


People also ask

How do I print a hex number without 0x in Python?

To print a positive or negative hexadecimal without the '0x' or '-0x' prefixes, you can simply use the string. replace('x', '0') method and replace each occurrence of 'x' with '0' . The resulting string is mathematically correct because leading '0' s don't change the value of the number.

How do you print a leading zero in hexadecimal?

Use "%02x" . The two means you always want the output to be (at least) two characters wide. The zero means if padding is necessary, to use zeros instead of spaces.

How do you print capitalized hex in Python?

Using %x conversion If you use %#x , the hexadecimal literal value is prefixed by 0x . To get an uppercase hexadecimal string, use %X or %#X .


2 Answers

>>> map("{:02x}".format, (10, 13, 15))
['0a', '0d', '0f']
like image 58
Senyai Avatar answered Oct 09 '22 10:10

Senyai


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)
like image 30
Andrew Clark Avatar answered Oct 09 '22 09:10

Andrew Clark