Integer as raw hex string?

R

Roy Smith

I have an integer that I want to encode as a hex string, but I don't
want "0x" at the beginning, nor do I want "L" at the end if it happened
to be a long. The result needs to be something I can pass to int(h, 16)
to get back my original integer.

The brute force way works:

h = hex(i)
assert h.startswith('0x')
h = h[2:]
if h.endswith('L'):
h = h[:-1]

but I'm wondering if there's some built-in call which gives me what I
want directly. Python 2.7.
 
T

Tim Chase

I have an integer that I want to encode as a hex string, but I don't
want "0x" at the beginning, nor do I want "L" at the end if it happened
to be a long. The result needs to be something I can pass to int(h, 16)
to get back my original integer.

The brute force way works:

h = hex(i)
assert h.startswith('0x')
h = h[2:]
if h.endswith('L'):
h = h[:-1]

but I'm wondering if there's some built-in call which gives me what I
want directly. Python 2.7.

Would something like

h = "%08x" % i

or

h = "%x" % i

work for you?

-tkc
 
R

Roy Smith

Tim Chase said:
I have an integer that I want to encode as a hex string, but I don't
want "0x" at the beginning, nor do I want "L" at the end if it happened
to be a long. The result needs to be something I can pass to int(h, 16)
to get back my original integer.

The brute force way works:

h = hex(i)
assert h.startswith('0x')
h = h[2:]
if h.endswith('L'):
h = h[:-1]

but I'm wondering if there's some built-in call which gives me what I
want directly. Python 2.7.

Would something like

h = "%08x" % i

or

h = "%x" % i

work for you?

Duh. Of course. Thanks.
 
M

MRAB

I have an integer that I want to encode as a hex string, but I don't
want "0x" at the beginning, nor do I want "L" at the end if it happened
to be a long. The result needs to be something I can pass to int(h, 16)
to get back my original integer.

The brute force way works:

h = hex(i)
assert h.startswith('0x')
h = h[2:]
if h.endswith('L'):
h = h[:-1]

but I'm wondering if there's some built-in call which gives me what I
want directly. Python 2.7.

Would something like

h = "%08x" % i

or

h = "%x" % i

work for you?
Or:

h = "{:x}".format(i)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top